jQuery中容易被疏忽的強大選取器和過濾器

來源:互聯網
上載者:User

標籤:style   io   color   ar   os   使用   sp   strong   div   

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> ]


jQuery中容易被疏忽的強大選取器和過濾器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.