CSS中:nth-child和JQuery:eq的区别

$("li:nth-child(n)")选择器与$("li:eq(n)")选择器的不同之处在于:
$("li:eq(n)")选择器只匹配一个元素,并且是所有匹配到的元素中的第n+ 1个元素(索引index从0开始算起);
$("li:nth-child(n)")选择器则先选择该元素所有父元素的第n个子元素,再判断是否满足要求(序号n从1开始算起),如果是就选择,否则不选择(满足条件的可能有多个)。

$("li:eq(-n)")选择倒数第n个元素,$("li:eq(-0)")选择正数第一个元素,$("li:eq(-1)")选择倒数第一个元素。

以下例子摘自https://blog.pivotal.io/labs/labs/css-first-child-nth-child-and-last-child-are-not-like-eq

if we had a snippet of HTML like

<div>
<div id="bar1" class="foo"></div>
<div id="bar2" class="foo"></div>
<div id="bar3" class="foo"></div>
</div>

Then the selector .foo:nth-child(2)will match the div #bar2. If we insert another element at the front of the container:

<div>
<p>Shift!</p>
<div id="bar1" class="foo"></div>
<div id="bar2" class="foo"></div>
<div id="bar3" class="foo"></div>
</div>

And again we select .foo:nth-child(2), we match the div #bar1 because the 2nd child of the container also matches .foo.

Thus, in this second example, if we try .foo:nth-child(1) or the equivalent .foo:first-child, we will not match any elements because the first child element in that container — the p tag — does not match .foo.

Likewise, :nth-child can match children in multiple containers. In the HTML snippet:

<div>
<p>Shift!</p>
<div id="bar1" class="foo"></div>
<div id="bar2" class="foo"></div>
<div id="bar3" class="foo"></div>
</div> <div>
<div id="quux" class="foo"></div>
</div>

the selector .foo:last-child will match the divs #bar3 and #quux; but .foo:first-child or .foo:nth-child(1) will only match #quux because the first child of the first container is, again, not a .foo.

上一篇:Java获取IP地址,IpUtils工具类,Java IP地址获取


下一篇:python的常用的内置函数