当使用 jquery 选择器时,我偶然发现了一些奇怪的事情。
我的 HTML:
<ul id="unordered-list">
<li>
<img src="https://www.google.com/images/srpr/logo4w.png" width="40" height="40"/>
<input type="text" size="40"/>
<input type="text" size="40"/>
</li>
<li>
<img src="https://www.google.com/images/srpr/logo4w.png" width="40" height="40"/>
<input type="text" size="40"/>
<input type="text" size="40"/>
</li>
</ul>
现在,如果我要选择第一个输入中的第一个输入来添加一些 css,我会使用这个:
$("#unordered-list li:nth-child(1) input:nth-child(1)").css("border", "5px solid red");
现在我认为浏览器会这样做:
1. 浏览器选择 #unordered-list
元素。
2. 然后浏览器选择第一个 li 元素。
3. 然后浏览器选择它找到的第一个输入元素。
但这并没有发生,它什么也没选择。
这是因为它实际上尝试选择 img,因为它是第一个子项。
查看JQuery nth:child的文档:
http://api.jquery.com/nth-child-selector/
他们做同样的事情:
<script>$("ul li:nth-child(2)").append("<span> - 2nd!</span>");</script>
这是一个演示该问题的工作 jsfiddle:
http://jsfiddle.net/uQYMz/
这似乎不合逻辑,我希望 input:nth-child(1) 选择第一个可用输入。这是预期的行为吗?如果是的话,选择这种行为的原因是什么?
最佳答案
这是 :nth-child
的定义来自 CSS 选择器规范:
The
:nth-child(an+b)
pseudo-class notation represents an element that has an+b-1 siblings before it in the document tree, for any positive integer or zero value of n, and has a parent element
它适用于同级集合中的所有元素,而不是特定类型的所有元素。还有另一个选择器,适当命名为 :nth-of-type
:
$("#unordered-list li:nth-child(1) input:nth-of-type(1)").css("border", "5px solid red");
这是一个updated fiddle .
<小时/>您可以按如下方式阅读原始选择器:
- 选择
#unordered-list
元素 - 如果
:nth-child(1)
处的元素是li
元素,则选择一个li
元素如果 - 如果
:nth-child(1)
处的元素是input
元素,则选择一个input
元素
关于jquery - CSS/JQuery 选择器奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17171163/