jQuery中选择器总体上包含了CSS3的选择器,但某些方面却由于CSS3的选择器,虽然使用各种选择器,最后也能达到目标,但在项目中,为了做的更少的代码量,使用某些特定的选择器,减少人为的判断似乎更加值得一试
1> :not(selector) 和 not(expr|ele|fn)
:not(selector)
not(expr|ele|fn)
$("input:not(:checked)")
对于not函数的用法
$("p").not('#selected') /*使用选择器*/
$("p").not( $("#selected")[0] ) /*使用 js DOM对象而不是jQuery对象*/
$('p').not(document.getElementById('selected'))
$("p").not(function(index){ //使用函数
return $(p).get(index)==$('#selected');
})
2> :eq(index)与eq(-index|index)
$("tr:eq(1)") #使用伪类选择器只能从正向0算起
$("p").eq(1) #从正向0算起
$("p").eq(-1) #从倒数第一位算起,起始值为 -1
3>:gt(index) 与lt:(index)
$("tr:gt(0)") #从上向下截取
$("tr:lt(5)") #从下向上截取
4>:animated用来过滤处于动画状态的元素
这里很多人做动画下拉菜单时容易出现闪烁,原因是没判断动画是否已停止
$("div:not(:animated)").animate({ left: "+=20" }, 1000); //这种情况几乎用不到,一般用到的是 和 is搭配
#下拉菜单判断
$('ul#dropmenu').hover(function(e){
if(!$(this).is(':animated')) /**不要担心动画停止不下来,从而强制使用stop,这样导致菜单卡主了很难看*/
{
$('ul#dropmenu').slideDown();
}
},function(e){
if(!$(this).is(':animated'))
{
$('ul#dropmenu').slideUp();
}
});
5>:hidden与:visibble
:hidden这个属性应该重点使用,因为他主要匹配2中DOM,一种是input[type=hidden],另一种是css display:hidden,特别是后一种,要重点使用,这样可以做切换效果
:visible不太重要,可以忽视
$("tr:hidden") //匹配css display=hidden
$("input:hidden") //匹配表达
6>:empty与empty()
:empty匹配所有不包含子元素或者文本的空元素,但是empty()是用来删除内容的,删除匹配的元素集合中所有的子节点。
$("td:empty")
$("p").empty();//等价于 $('p').html('');
7>:has(selector)与has(selector|element)
用来过滤
$('li').has('ul').css('background-color', 'red'); //过滤包含 ul的 li
$('li:has("ul"').css('background-color',red);
8>andself()
包含自己,通常用来杀个回马枪,比如找出兄弟节点在加上自己
<div><p>First Paragraph</p><p>Second Paragraph</p></div>
$("div").find("p").andSelf().addClass("border"); //将div本身加入
9.siblings([selector]),prevAll([selector]),nextAll([selector]);
获取兄弟节点
10.slice(start,end)
切片过滤器
HTML 代码:
<p>Hello</p><p>cruel</p><p>World</p>
jQuery 代码:
$("p").slice(0, 1).wrapInner("<b></b>");
结果
[ <p><b>Hello</b></p> ]