今天闲的没事去翻了翻JQuery的中文文档,被jQuery的强大的选择器震撼的同时,我也为个别的选择器感觉到很迷惑,感觉相互之间没有什么区别啊,为什么要不同啊。就拿first-child和first-of-type来说,自己写的测试方法,返回的结果完全一样,让我更感觉迷惑,通过查询相关的资料,终于让我搞清楚了。
<!DOCTYPE html>
<html>
<head>
<title>jQuery中的小知识:first-child和first-of-type的区别</title>
<script type ="text/javascript" src = "./js/jquery.1.10.2.js"></script>
</head>
<body>
<a></a>
<p>我的父亲是body我是P1</p>
<p>我的父亲是body我是P2</p>
<p>我的父亲是body我是P3</p>
<div>
<p>我的父亲是div1我是Pd1</p>
<a>我的父亲是div1我是a1</a>
<!--这里可以把Pd1和a1掉一下位置进行前后对比,会进一步的认识两者的区别-->
<p>我的父亲是div1我是Pd2</p>
<p>我的父亲是div1我是Pd3</p>
</div>
<div>
<p>我的父亲是div2我是Pd1</p>
<p>我的父亲是div2我是Pd2</p>
<p>我的父亲是div2我是Pd3</p>
</div>
<div>
</div>
<button id="reset">reset</button>
<button id="first-of-type">:first-of-type</button>
<button id="first-child">:first-child</button>
</body>
<script>
$(function(){
$("#reset").on("click",function(){
$("p").css("background-color","white");
})
//寻找的是所有同级别的兄弟之间的是:之前的元素的第一个元素
$("#first-of-type").on("click",function(){
$("p:first-of-type").css("background-color","yellow");
})
//寻找的是所有同级别的第一个元素是:之前的元素的所有元素,
//也就是先获取所有的同级别的第一个元素,取其中的元素是给定选择器的元素的所有元素
$("#first-child").on("click",function(){
$("p:first-child").css("background-color","red");
})
});
</script>
</html>
通过这个Demo,我们是不是可以很清楚的比较出两者之间的区别。