【问题标题】:jQuery :first-child Not Working As ExpectedjQuery:第一个孩子没有按预期工作
【发布时间】:2012-05-24 16:47:39
【问题描述】:

我有一个看起来像这样的表格:

jsFiddle

<ul id="services">
<li class="service"><label><input type="checkbox">A single option</label>
</li>
<li class="service"><label><input type="checkbox">Another single option</label>
<ul>
    <li>
    <select>
    </select>
     additional options</li>
</ul>
</li>
<li class="service"><label>
<select>
</select>
A multiple option</label>
<ul>
    <li><label><input type="checkbox"> with another option </label>
    <select>
    </select>
    </li>
</ul>
</li>
<li class="service"><label>
<select>
</select>
Another multiple option</label>
<ul>
    <li><label><input type="checkbox"> with another option </label>
    <select>
    </select>
    </li>
    <li>
    <select>
    </select>
     additional options</li>
</ul>
</li>

​​​ 我正在尝试使用以下方法仅选择&lt;li&gt;s 的第一级中的&lt;label&gt;s 和“服务”类:

$(".service label:first-child").css("background", "yellow");​

但它似乎是递归的,并且正在选择嵌套&lt;ul&gt;s 的第一个孩子。

我在这里做错了什么?如何只选择具有“服务”类的&lt;li&gt;s 的第一级中的&lt;label&gt;s?

【问题讨论】:

    标签: jquery jquery-selectors css-selectors


    【解决方案1】:
    $(".service > label").css("background", "yellow");​
    

    Fixed DEMO


    &gt; 是直接子选择器。

    所以a &gt; b选择器意味着,只有当它的直接父是a时才选择b

    w3 spec:

    8.2。子组合器

    子组合子描述了两个元素之间的童年关系。子组合器由“大于号”(U+003E, >) 字符组成,用于分隔两个简单选择器序列。


    :first-child 选择器的意思是,选择它的父元素的第一个子元素。

    w3spec:

    6.6.5.6。 :first-child 伪类

    与 :nth-child(1) 相同。 :first-child 伪类表示一个元素,它是某个其他元素的第一个子元素。

    【讨论】:

      【解决方案2】:

      您需要明确表示您想要孩子,来自父母而不是所有孩子

       $(".service > label").css("background", "yellow");​
      

      Live Example

      【讨论】:

        【解决方案3】:

        $("#services&gt;li&gt;label").css("background", "yellow");​

        要仅获取直接子级,请使用 &gt;

        您可以在此处获取有关选择器的更多信息:http://www.w3schools.com/cssref/css_selectors.asp

        我认为你的 jsfiddle 有一些问题,但如果你只想到 li 的第一级,这就是你需要做的。

        【讨论】:

        • 选择器中的: 应该做什么?
        • 复制粘贴问题.. 已删除。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-17
        • 2019-07-13
        • 2012-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多