匹配最多的HTML元素是表单元素,jQuery也推出了专门用来匹配表单元素的选择器。
表单选择器:
:input
匹配所有 input, textarea, select 和 button 元素
$(":input")
<form>
<input type="button" value="Input Button"/>
<input type="checkbox" />
<input type="file" />
<input type="hidden" />
<select><option>Option</option></select>
<textarea></textarea>
<button>Button</button>
</form>
注意与$("input")的区别
<form>
<input type="button" value="Input Button"/>
<input type="checkbox" />
<input type="file" />
<input type="hidden" />
<select><option>Option</option></select>
<textarea></textarea>
<button>Button</button>
</form>
:text
匹配所有的单行文本框
$(":text")
<form>
<input type="text" />
<input type="checkbox" />
<input type="radio" />
<input type="button" />
<select><option/></select>
<textarea></textarea>
<button></button>
</form>
:password
匹配所有密码框
:radio
匹配所有单选按钮
:checkbox
匹配所有复选框
:reset
匹配所有重置按钮
:submit
匹配所有提交按钮
:image
匹配所有图像域
:file
匹配所有文件域
:button
匹配所有按钮
$(":button")
<form>
<input type="text" />
<input type="button" />
<select><option/></select>
<textarea></textarea>
<button></button>
</form>
表单属性过滤器:
:checked
匹配所有选中的被选中元素(复选框、单选框等,不包括select中的option),这个过滤器用得蛮多的。
$("input:checked")
<form>
<input type="checkbox" name="newsletter" checked="checked" value="Daily" />
<input type="checkbox" name="newsletter" value="Weekly" />
<input type="checkbox" name="newsletter" checked="checked" value="Monthly" />
</form>
:disabled
匹配所有不可用元素
$("input:disabled")
<form>
<input name="email" disabled="disabled" />
<input name="id" />
</form>
:enabled
匹配所有可用元素
$("input:enabled")
<form>
<input name="email" disabled="disabled" />
<input name="id" />
</form>
:selected
匹配所有选中的option元素,这个比较常用。
$("select option:selected")
<select>
<option value="1">Flowers</option>
<option value="2" selected="selected">Gardens</option>
<option value="3">Trees</option>
</select>
选择器大总结:
用了六节的内容把所有的选择器介绍完毕。学习选择器我们要弄懂为什么学习它?它的作用就像JS中的节点对象,在jQuery中对HTML元素操作第一步先写一个能匹配到它的选择器。
jQuery中的选择器虽然很多,大部分选择器都不是唯一的(非它匹配不到某个元素),功能是重复的。所以我们没必要全记住,先记住常用的几个就能完成绝大数的功能。常用的有:
基本选择器
$('#id属性值')
$('tag标签名称')
$('.class属性值')
层级选择器
$(s1 s2)
$(s1 > s2)
基本过滤器
:even
:odd
:eq(index)
:gt(index)
:lt(index)
属性过滤器
[attribute=value]
表单属性过滤器
:checked
:selected
jQuery手册中对选择器介绍得非常好,在实际应用中大家可多参考着手册选择使用哪个选择器。