关于jQuery中nth-child和nth-of-type的详解

首先贴出来HTML的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    var btn = $(this).text();
    $("p").css("background-color","white"); 
    $("p" + btn).css("background-color","yellow");  
  });
});
</script>

</head>
<body>
<button>:nth-child(2)</button>
<button>:nth-last-child(2)</button>
<button>:nth-of-type(2)</button>
<button>:nth-last-of-type(2)</button>

<h1>body 中的标题</h1>
<p>body 中第一个段落。</p>
<p>body 中第二个段落。</p>

<div style="border:1px solid;">
    <span>div 中的 span 元素</span>
    <p>div 中的第一个段落。</p>
    <p>div 中的第二个段落。</p>
    <p>div 中的第三个段落。</p>
    <p>div 中的第四个段落。</p>
    <span>div 中的 span 元素</span>
</div><br>

<div style="border:1px solid;">
    <p>另一个 div 中的第一个段落。</p>
    <p>另一个 div 中的第二个段落。</p>
    <p>另一个 div 中的最后一个段落。</p>
</div>

<p>body 中最后一个段落。</p>



</body>
</html>

整个页面的显示结果为:

请回答从左往右分别点击按钮哪几行会出现背景颜色的变化呢?

点击第一个:

4,10

点击第二个:

7,10

点击第三个:

2,5,10

点击第四个:

2,6,10

你回答正确了吗?如果正确可以点击右上角关闭网页了.

由此可以看出

A:nth-child(B)表示在父元素的第B个元素刚好是A的所有A元素

A:nth-of-type(B) 表示父元素的第B个A元素的所有A元素集合

看出来区别了吗?nth-of-type实质上在索引时进行了一次筛选,父元素只包含A,所以只要B < A在父元素中的数量就一定有值,而nth-child没有进行筛选,是父元素中所有元素的第B个,如果是A则取出来, 有可能就取不到.

如果你能理解以上的问题,那么对eq()的区别也显而易见了,A:eq(B),选出的所有A中的第B个,跟父元素就没关系了.

原文地址:https://www.cnblogs.com/BigJ/p/8582977.html