1 定义

与Xpath选择器十分详细。在简介中通过css选择器,能够锁定目标元素。

2 向上遍历

  • parent()
  • parents()
  • parentsUntil()
1
2
3
4
5
6
7
$(document).ready(function(){
$("span").parents("ul");
});

$(document).ready(function(){
$("span").parentsUntil("div");
});

3 向下遍历

  • children()
  • find()
1
2
3
4
5
6
7
$(document).ready(function(){
$("div").children();
});

$(document).ready(function(){
$("div").find("span");
});

4 水平遍历

  • siblings()
  • next()
  • nextAll()
  • nextUntil()
  • prev()
  • prevAll()
  • prevUntil()
1
2
3
4
5
6
7
8
9
10
11
$(document).ready(function(){
$("h2").siblings();
});

$(document).ready(function(){
$("h2").next();
});

$(document).ready(function(){
$("h2").nextUntil("h6");
});

5 遍历过滤

  • first(), last() 和 eq(),它们允许您基于其在一组元素中的位置来选择一个特定的元素。
  • filter() 和 not() 允许您选取匹配或不匹配某项指定标准的元素。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$(document).ready(function(){
$("div p").first();
});
$(document).ready(function(){
$("div p").last();
});
$(document).ready(function(){
$("p").eq(1);
});
$(document).ready(function(){
$("p").filter(".url");
});
$(document).ready(function(){
$("p").not(".url");
});

6 遍历each

遍历所有的子元素。回调函数的两个参数分别是下标和dom对象

1
2
3
4
5

$('selector').each(function(index,element){
//可以将dom对象转换为jQuery对象
$(element)
})