這次學習的是過濾器,其實也是選擇器。jQuery的過濾器,很類似於CSS的僞類。
基本過濾器
說明:書寫時,注意“:”前邊是否有空格。沒有空格,代表當前元素。有空格,代表後代選擇器。
$(document).ready(function(){ $('li:first').css('background','green'); //第一個li元素,背景色爲綠色 $('li:last').css('background','green'); //最後一個li元素,背景色爲綠色 $('li:not(".childItem")').css('background','green'); //類不是.childItem的元素,背景色爲綠色 $('li:even').css('background','green'); //索引是偶數的li元素,背景色爲綠色 $('li:odd').css('background','green'); //索引是基數的li元素,背景色爲綠色 $('li:eq(2)').css('background','green'); $('li:eq(2)').css('background','green'); //index爲2的li元素,背景色爲綠色 $('li:gt(3)').css('background','green'); //index>3的li元素,背景色爲綠色 $('li:lt(3)').css('background','green'); //index<3的li元素,背景色爲綠色 $('input').focus(); $('input:focus').css('background','green'); //將當前獲得焦點的元素,背景色爲綠色 })
對常用的選擇器,jQuery提供了方法:
$(document).ready(function(){ $('li').first().css('background','green'); //first()方法 $('li').last().css('background','green'); //last()方法 $('li').not('.childItem').css('background','green'); //not()方法 $('li').eq(2).css('background','green'); //eq()方法 $('li').eq(2).css('background','green'); //eq()方法 })
內容過濾器
注意:“:parent”和jQuery提供的方法parent()之間是有區別的
“:parent”:有子元素或文本的當前元素
“parent()”:當前元素的父元素$(document).ready(function(){ $('div:contains("歡迎")').css('background','yellow'); //包含"歡迎"的div,背景色爲黃色 $('div:empty').css('background','purple').css('height','20px'); //空的子元素,背景色爲紫色 $('ul:has(.childItem)').css('background','orange'); //包含類childIteml的ul,背景色爲橘色 $('#address:parent').css('background','pink'); //有文本的div,背景色爲橘色 $('.childItem').parent().css('background','yellow'); //當前元素的父元素,背景色爲黃色 $('#address').parents().css('background','green'); //當前元素的父及祖元素,背景色爲綠色 $('li').parentsUntil('div').css('background','pink'); //當前元素遇到‘div’,即停止 })
可見性過濾器
$(document).ready(function(){ $('div:hidden').show(); //隱藏的元素,顯示 alert($('li:visible').size()); //顯示的元素,數量 })
子元素過濾器
$(document).ready(function(){ $('li:first-child').css('background','yellow'); //父元素的第一個li元素,背景色爲黃色 $('li:last-child').css('background','pink'); //父元素的最後一個li元素,背景色爲粉色 $('li:only-child').css('background','green'); //父元素只有一個li元素,背景色爲綠色 $('li:nth-child(even)').css('background','yellow'); //父元素偶數的li元素,背景色爲黃色 $('li:nth-child(odd)').css('background','pink'); //父元素奇數的li元素,背景色爲粉色 $('li:nth-child(2)').css('background','green'); //父元素的第2個li元素,背景色爲綠色 })
其他方法
$(document).ready(function(){ alert($('.childItem').is('li')); //檢測class,是否爲“childItem” alert($('.childItem').is($('li'))) //同上 alert($('.childItem').is($('li').get(2))) //同上 $('.childItem').is(function(){ //同上 return $(this).attr("title") == '列表三'; }); alert($('li').eq(2).hasClass('childItem')); //同上 $('li').slice(0,2).css('background','purple'); //前兩個li元素,背景色爲紫色 $('li').filter('.childItem').css('background','yellow'); //類爲“childItem”的li元素,背景色爲黃色 $('li').filter(':first,:last').css('background','green'); //過濾第一個,最後一個li元素,背景色爲綠色 $('li').filter(function(){ //根據條件過濾,背景色爲藍色 return $(this).attr('class')=='childItem' && $(this).attr('title') == '列表三'; }).css('background','blue'); })