jQuery 选择器
1、列举 jquery常见选择器的用法
<body>
<div class="box1"></div>
<div class="box2">
<h1 class="title"></h1>
<p class="content"></p>
</div>
<div class="box3"></div>
</body>
.eq(index):获取到指定index的jQuery对象
$('div').eq(2); // 获取结果集中的第四个jQuery对象,[div.box3, prevObject: n.fn.init(10), context: document]
.get(index):获取指定index的DOM对象,也就是我们说的jQuery对象转DOM对象,等同于[index]
$('div').get(2);//<div class="box3"></div>
$('div')[2];//<div class="box3"></div>
兄弟元素的获取
.next([selector]), .prev([selector]):下个/上个兄弟元素的获取。如果提供一个选择器,那么只有紧跟着的兄弟元素满足选择器时,才会返回此元素
$('.box2').next();//[div.box3, prevObject: n.fn.init(1), context: document]
$('.box2').prev();//[div.box1, prevObject: n.fn.init(1), context: document]
$('.box2').next('.box3');//[div.box3, prevObject: n.fn.init(1), context: document]
$('.box2').next('.box4');//[prevObject: n.fn.init(1), context: document],未找到
.nextAll([selector]), .prevAll([selector]):nextAll获得元素后面的所有的兄弟元素,prevAll与之相反,获取元素前面的所有的兄弟元素
$('.box1').nextAll();//[div.box2, div.box3, script, script, script, script, script, prevObject: n.fn.init(1), context: document]
$('.box1').nextAll('.box3');//[div.box3, prevObject: n.fn.init(1), context: document]
.siblings([selectors]):获取元素所有的兄弟元素
$('.box2').siblings();//[div.box1, div.box3, script, script, script, script, script, prevObject: n.fn.init(1), context: document]
父子元素获取
.parent([selector]),.parents([selector]):获取父元素,获取所有的祖辈元素
$('.title').parent();//[div.box2, prevObject: n.fn.init(1), context: document]
$('.title').parents();//[div.box2, body, html, prevObject: n.fn.init(1), context: document]
.children([selector]):获取子元素
$('.box2').children();//(2) [h1.title, p.content, prevObject: n.fn.init(1), context: document]
.find([selector]):查找符合选择器的后代元素
$('.box2').find('p');//[p.content, prevObject: n.fn.init(1), context: document, selector: ".box2 p"]
筛选当前结果集
.first(),.last():获取当前结果集中的第一个;对象获取当前结果集的最后一个对象
$('div').first();//[div.box1, prevObject: n.fn.init(4), context: document]
.filter(selector), .filter(function(index)):筛选当前结果集中符合条件的对象,参数可以是一个选择器或者一个函数
$('div').filter(':even');//[div.box1, div.box3, prevObject: n.fn.init(3), context: document]
$('div').filter(function(index) {
return index % 3 == 2;
})//[div.box3, prevObject: n.fn.init(3), context: document]
.not(selector), .not(function(index)):从匹配的元素集合中移除指定的元素,和filter相反
$('div').not('.box2');//[div.box1, div.box3, prevObject: n.fn.init(3), context: document]
.is(selector), is(function(index)), is(dom/jqObj)
判断当前匹配的元素集合中的元素,是否为一个选择器,DOM元素,或者jQuery对象,如果这些元素至少一个匹配给定的参数,那么返回true
console.log($('div').is("li"))//false
console.log($('.box2').is(":even"))//true
.has(selector), .has(dom):筛选匹配元素集合中的那些有相匹配的选择器或DOM元素的后代元素
$('div').has('h1');//[div.box2, prevObject: n.fn.init(3), context: document]