这次学习的是过滤器,其实也是选择器。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'); })