0

我如何能够选择与第 1 层相关的第一个、第二个和第三个跨度,独立于它是否是第 2 层的 div 的第一个子项?

<div class="LAYER1">
  <div class="LAYER2">
    <span>FIRST<span>
  </div>
  <div class="LAYER2">
    <span>SECOND</span>
    <span>THIRD</span>
  </div>
</div>

通过使用span:first-child我得到 FIRST 和 SECOND,但我只想得到 FIRST。

编辑:我的目标是做出“让我从 LAYER1 获得第一个、第二个和第三个跨度孩子”之类的选择。SECOND 和 THIRD 也可以在第一个 LAYER2 div 中,解决方案不应依赖于此。

EDIT2: http: //jsfiddle.net/3hAEc/3/的示例

4

4 回答 4

2

选择只能<span>FIRST</span>像这样工作(假设浏览器支持它)

.LAYER1 .LAYER2:first-child span { 
    // ...
}

正如你在这里看到的:http: //jsfiddle.net/3hAEc/

于 2013-05-21T20:09:44.893 回答
0

您如何向它们添加 id 或类,然后以这种方式选择它们?

<div class="LAYER1">
  <div class="LAYER2">
    <span id="first_span">FIRST<span>
  </div>
  <div class="LAYER2">
    <span id="second_span">SECOND</span>
    <span id="third_span">THIRD</span>
  </div>
</div>
于 2013-05-21T20:01:49.873 回答
0

尝试这个 :

.LAYER1 .LAYER2:first-child span:first-child /* first one*/
.LAYER1 .LAYER2+.LAYER2 span:first-child /* second one*/
.LAYER1 .LAYER2+.LAYER2 span:first-child+span /* third one*/

但这仅适用于当前的 DOM。

于 2013-05-21T20:01:57.857 回答
0

最后,我通过 jQuery 使用了以下 JS 解决方案:

// for the first span, use 0 and increase for further children
$(".LAYER1").find("span").eq(0);
于 2013-05-21T20:47:29.537 回答