jQuery 选择器大概分为:
1.属性选择器
比如存在一组input 表单 :
<form id="formID">
1. <input type="tel" placeholder="tel">
2. <input type="text" placeholder="text">
3. <input type="tel" placeholder="tel">
4. <input type="date" placeholder="date">
5. <input type="password" placeholder="password">
6. <input type="button" placeholder="button">
7. <input type="radio" placeholder="radio" >
8. <input type="checkbox" placeholder="checkbox">
9. <input type="email" placeholder="email">
10. <input type="file" placeholder="file">
</form>
上面一共有10个表单元素,
1. 查找含有type的input的个数: $("input[type]").length 打印结果为:10 ;
2. 查找含有type=tel的input的个数:$("input[type='tel']").length 打印结果为:2 ;
3.查找type以t开头的个数 :$("input[type^='t']").length 打印结果为:3 ;
4.查找type以l结尾的个数 :$("input[type$='l']").length 打印结果为:3 ;
5.查找type以tel开头或者等于tel的个数 :$("input[type|='tel']").length 打印结果为:2 ;
6.查找type包含tel的个数 :$("input[type~='tel']").length 打印结果为:2 ;
2.表单选择器
3.位置选择器
<table border="2" style="border-collapse: collapse;">
<tr>
<td>姓名</td>
<td>年龄</td>
<td>地址</td>
</tr>
<tr>
<td>客户给对方</td>
<td>23</td>
<td>规范风格的风格的风格的覆盖非</td>
</tr>
<tr>
<td>客户给对方111111</td>
<td>23</td>
<td>规范风格的风格的风格的覆盖非</td>
</tr>
<tr>
<td>客户给对方222333333333</td>
<td>23</td>
<td></td>
</tr>
<tr>
<td>客户给对方5555555</td>
<td>23</td>
<td></td>
</tr>
<tr>
<td>李银凤111</td>
<td>23</td>
<td>规范风格的风格的风格的覆盖非</td>
</tr>
</table>
应用实例:
设置第一行背景色为红色 $("tr:first").css("background","#fa0000");
设置索引为偶数的行背景色为灰色:$("tr:odd").css("background","#bbb");
设置第一行小于3的前三个单元格字体颜色为白色:$("tr:eq(0) > td:lt(3)").css("color",'#fff')
设置第五行的最后一个单元格背景色为绿色: $("tr:nth-child(5) > td:last").css("background",'green')
实例截图:
4.可见性选择器
disabled:none; DOM节点消失
visibility: hidden; 占位隐藏
不可见的元素个数:"+$("a:hidden").length
可见的元素个数:"+$("a:visible").length
5.内容选择器
应用上面的table表格与form表单:
td里面含有客户给对方字段的个数"+$("td:contains('客户给对方')").length 结果为:4
获取含有input的form表单的id: $("form:has(input)").attr('id')
区分 :empty :parent
观察会发现上面一共有18个td单元格,其中2个为空的,我们觉得应该一个值为2,一个为16,
但是为什么打印的数值是1和17,
请看这里
一个有换行出现,一个没有,但是文本元素为空元素(满足 :empty)的只有第一个
6.自定义选择器
<div id="divid1" class="divclass">白色</div>
<input type="button" value="按钮[绿色]" id="but1" />
// 5. 自定义选择器
function expr(){
$.expr[":"].greenbg = function (obj) {
if (obj.style.backgroundColor === "green")
return $(obj).css("background-color", "white"), $(obj).text("白色");
return $(obj).css("background-color", "green"), $(obj).text("绿色");
};
}
$("#but1").click(function () {
$("#divid1:greenbg");
});