jQuery 過濾not()與filter()執行個體代碼

來源:互聯網
上載者:User

第一種寫法:
複製代碼 代碼如下:
$(function(){
$("li").not(":even").css("color","red");
$("li").filter(":odd").css("color","red");

})

第二種寫法:
複製代碼 代碼如下:
$(function(){
$("li").filter(function(index) {
return index%2 == 0;
}).css("color","red");

$("li").not(function(index) {
return index%2 !== 0;
}).css("color","red");
})

這兩種寫法,都可以達到一樣的效果,not與filter是相反的過濾!

jQuery過濾選取器:not()方法介紹

jQuery(':not(selector)')
在jQuery的早期版本中,:not()篩選器只支援簡單的選取器,說明我們傳入到:not這個filter中的selector可以任意複雜,比如:not(div a) and :not(div,a)

<p >"a">sdfsdfs</p>
<p >"b">sdfsdfs</p>
<p >"c">sdfsdfs</p>

$("p:not(.a)").css({"color":"red"})
那麼除了class等於a的p元素外,其他的P的文字顏色就變成了紅色.
:not()偽類過濾選取器,這叫法真拗口,jQuery的:not()方法是jQuery的偽類別選取器,可以過濾不需要的元素,篩選出正確的結果,簡單的說我們有如下代碼:

$("selector1:not(selector2)")
我們分析下上面的代碼,我們要擷取selector1的元素,但可能我不需要全部,怎麼辦,通過:not()方法來過濾,如果selector1的集合中有#1,#2,#3,#4
我們的selector2就是要過濾掉#4,上面的代碼我們最終將獲得#1,#2,#3
再舉幾個列子

$('li:not(:only-child)')//匹配所有的li,除了只有一個子項目的
$('li:not(:first-child)');//匹配除了在他父元素中是第一個子項目的LI
$("li :not(:first)").hide();//隱藏除了第一個LI外的所有LI

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.