0

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

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>

​并且我试图通过使用以下方法仅选择具有“服务”类的<label>s 的第一级中的s:<li>

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

但 is 似乎是递归的,并且正在选择嵌套<ul>s 的第一个孩子。

我在这里做错了什么?如何仅选择具有“服务”类<label>的 s 的第一级中的s?<li>

4

3 回答 3

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

Fixed DEMO


> is direct child selector.

so a > b selector means, select b only if it's direct parent is a.

w3 spec:

8.2. Child combinators

A child combinator describes a childhood relationship between two elements. A child combinator is made of the "greater-than sign" (U+003E, >) character and separates two sequences of simple selectors.


:first-child selector means, select the element which is the first child of it's parent.

w3spec:

6.6.5.6. :first-child pseudo-class

Same as :nth-child(1). The :first-child pseudo-class represents an element that is the first child of some other element.

于 2012-05-24T16:51:26.333 回答
1

you need to be explicit that you want the children, from the parent and not all the childs

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

Live Example

于 2012-05-24T16:52:50.533 回答
0
于 2012-05-24T16:48:50.443 回答