3.2.5 表单相关的选择器

3.2.5 表单相关的选择器

以下各选择器专门用于匹配各种表单控件。

:input选择符

:input:返回由所有inputtextareaselectbutton元素包装成的jQuery对象。
提示:该选择器已经过时了,因为它不是CSS规范里的,只是jQuery的扩展选择器,所以它不能利用原生DOM的性能优势,故性能较差。如果希望使用该选择器,则可以考虑使用.filter(":input")方法来代替。

过时了的选择符

下列选择器已经过时了,因为它不是CSS规范里的,只是jQuery的扩展选择器,不能利用原生DOM的性能优势,故性能较差。如果希望使用该选择器,则可以考虑使用[type="xxxx"]的属性选择器代替。如

  • :text,使用[type="text"]属性选择器替代.
  • :password使用[type="password"]属性选择器替代

:text

:text:返回由所有type="text"input元素包装成的jQuery对象。

:password

:password:返回由所有type="password"input元素包装成的jQuery对象。

:radio

:radio:返回由所有type="radio“的input元素包装成的jQuery对象。

:checkbox

:checkbox:返回由所有type="checkbox"input元素包装成的jQuery对象。

:submit

:submit:返回由所有type="submit"input元素包装成的jQuery对象。

:image

:image:返回由所有type="image"input元素包装成的jQuery对象。

:reset

:reset:返回由所有type="reset"input元素包装成的jQuery对象。

:button

:button:返回由所有按钮元素(包括type="button"input元素)包装成的jQuery对象。

:file

:file:返回由所有文件域包装成的jQuery对象。

没有过时的选择符

:hidden

:hidden:返回由所有不可见元素以及指定了type="hidden"input元素包装成的jQuery对象。
:hidden选择器不仅可以匹配表单控件,而且还可以匹配所有不可见的元素,包括<meta..../>等元素。

:enabled

:enabled:返回由所有可用的(未指定disabled属性)的表单控件包装成的jQuery对象。

:disabled

:disabled:返回由所有不可用的(指定了disabled 属性)的表单控件包装成的jQuery对象。

:checked

:checked:返回由所有指定了checked属性的表单控件包装成的jQuery对象。

:selected

:selected:返回由所有指定了selected的表单控件包装成的jQuery对象。

程序示例

下面的程序示范了上述选择器的用法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html>
<head>
<meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> 使用jQuery()函数 </title>
</head>
<body>
<input id="user" type="text" />
<br />
<input id="pass" type="password" />
<br />
<textarea id="intro"></textarea>
<br />
<select id="gender" size="3" style="width:80px">
<option value="male" selected></option>
<option value="female"></option>
</select>
<p>
<input id="pass" type="checkbox" checked value="xx" />
<br />
<script type="text/javascript" src="../jquery-3.1.1.js">
</script>
<script type="text/javascript">
// 获取所有的input、textarea、button元素,并设置value属性为test
$(":input:not('select')").val("test");
// 获取所有指定了selected属性的元素
$(":selected").css("border", "2px dashed black");
// 获取所有指定了checked属性的元素,并取消它们的选中
$(":checked").prop("checked", false);
</script>
</body>
</html>