GVi*_*i82 2 html javascript jquery jquery-selectors
一个简单的例子让我对jQuery中的选择器感到困惑.我有这个HTML代码:
<div class="container">
<h1>Welcome to my Website </h1>
<p>First paragraph</p>
<p>Second paragraph</p>
</div>
Run Code Online (Sandbox Code Playgroud)
如果我想突出第二个段落,我认为这是正确的方法:
$('p:nth-child(2)').css("background-color","yellow");
Run Code Online (Sandbox Code Playgroud)
但这是不正确的,事实上第一段将被突出显示,即使我只有两个<p>部分,我将值2放在nth-child()函数内.
如果我删除<h1>元素,第二段将突出显示.因此,似乎该<h1>元素被<p>jQuery选择器视为元素.
但是代码:
$('p:nth-child(1)').css("background-color","yellow");
不会突出任何事情.为什么会这样?
nth-child意思是"孩子到位n ",你正在寻找的是什么nth-of-type,看看:http://css-tricks.com/the-difference-between-nth-child-and-nth-of-type/
所以这个将按预期工作:
$('p:nth-of-type(2)').css("background-color","yellow");
Run Code Online (Sandbox Code Playgroud)
JSFiddle:http://jsfiddle.net/t2rn7/