jquery - CSS/JQuery 选择器奇怪的行为

标签 jquery css jquery-selectors css-selectors

当使用 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/

相关文章:

javascript - jquery Tiny Colorpicker 事件更改

javascript - 使用 CSS-Element-Queries 库模拟 CSS 的媒体查询

html - 无法在 css <div> 页脚上居中放置文本

jquery - 如何使用 jQuery 过滤不需要的元素

css - 在复杂的 jQuery/CSS3 选择器中使用 TILDE

jQuery Owl Carousel 2 隐藏导航

javascript - 如何实现最大限度的用户友好的日期输入?

jquery - 悬停在第三级 li 上时,在导航栏中突出显示第二级 li

jquery - 将数组值传递给 jQuery 选择器方法?

javascript - 搜索具有共同祖先的项目