$("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.
