相关文章:

jQuery 选择器(:nth-child(n))详解

代码类型:

杂项:

  • 启用CSS/JS语法检查
  • 监测脚本运行错误
  • 禁止库文件重复

文档类型:

JS库文件:

手动添加:

  1. jQuery 1.11.1
 
1
<div id="n1">
2
    <div id="n2">
3
        <ul id="n3">
4
            <li id="n4" class="c">item1</li>
5
            <li id="n5">item2</li>
6
            <li id="n6" class="c">item3</li>
7
        </ul>
8
    </div>
9
    <div id="n7">
10
        <ul id="n8">
11
            <li id="n9">item1</li>
12
            <li id="n10">item2</li>
13
        </ul>
14
    </div>
15
</div>
xxxxxxxxxx
28
 
1
// 扩展jQuery对象,添加showTagInfo()方法
2
// 用于将jQuery对象所有匹配元素的标识信息追加到body元素内
3
// 每个元素的标识信息形如:"tagName"或"tagName#id"
4
jQuery.fn.showTagInfo = function(){
5
    var tags = this.map( function(){
6
        return this.tagName + ( this.id ? "#" + this.id : "" ); 
7
    } ).get();
8
    $("body").append( "<br>" + tags.join("<br>") + "<br>" );
9
};
10
11
12
13
// 选择了id分别为n5、n10的两个元素
14
$("ul li:nth-child(2)").showTagInfo();
15
16
17
// 选择了id分别为n4、n6、n9的3个元素
18
$("ul li:nth-child(odd)").showTagInfo();
19
20
21
// 选择了id为n6的一个元素
22
// 虽然这里用的#n1进行限定,实际上jQuery先是通过查找所有匹配#n1 li的元素,然后再看这些元素是不是父元素的第3n个元素,如果是就保留,否则就舍弃掉。
23
$("#n1 li:nth-child(3n)").showTagInfo();
24
25
26
// 没有选择任何元素,返回空的jQuery对象
27
// 虽然匹配li.c的有n4、n6两个元素,但它们都不是父元素的偶数顺序的子元素,因此无法匹配
28
$("li.c:nth-child(even)").showTagInfo();
x
 
1