【问题标题】:Getting nth:child of specific element type获取 nth:child 特定元素类型
【发布时间】:2018-06-03 23:20:49
【问题描述】:

示例代码:

<div id="top">
    <h1></h1>
    <div></div>
    <h2></h2>
    <div>Get this one</div>
    <h3></h3>
    <div></div>
</div>

所以我知道我可以使用

$('#top:nth-child(4)').etc...

但是我可以通过说“获取作为 div 元素的第二个子元素”而不是仅仅“获取第四个子元素”来得到这个吗?

希望这是有道理的。

【问题讨论】:

  • $('#top:nth-child(4)') 将选择一个 ID 为 #top 的元素,该元素也是其父元素的第四个子元素。 $('#top &gt; :nth-child(4)') 将选择该 div

标签: jquery css css-selectors


【解决方案1】:

是的,nth-of-type 与标签类型本身相关(在本例中为 div),而不是一般的类或子元素:

$('#top > div:nth-of-type(2)').etc.

在评论中附加问题后添加:

您不能使用 CSS 选择器选择具有特定类的第 n 个 DIV,而是使用 jQuery。

$("#top > div.x").eq(1).css("color", "blue");

eq() 选择集合中的第 n 个元素(即在之前所做的选择中)。注意它的索引从 0 开始,所以eq(1)选择集合中的第二个元素:

$("#top &gt; div.x").eq(1).css("color", "blue");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="top">
    <h1>H1</h1>
    <div class="x">1st DIV with class "x"</div>
    <h2>H2</h2>
    <div>DIV</div>
    <h3>H3</h3>
    <div>DIV</div>
    <div class="x">2nd DIV with class "x"</div>
    <h2>H2</h2>
    <div>DIV</div>
    <h3>H3</h3>
    <div class="x">3rd DIV with class "x"</div>
</div>

【讨论】:

  • 如果我想更具体一点,说 div 和某个类怎么样?那可行吗?会是 $('#top > div.classname:nth-of-type(2)') 吗?
  • CSS 选择器无法做到这一点
  • 请注意,我为您的第二个答案添加了一个可行的解决方案
【解决方案2】:

$('#top &gt; div')[1]$('#top &gt; div').get(1) 会做你想做的事。它说“在#top 中立即 抓取 div,然后选择第二个。” $('#top div')(连同.get(1))在这种情况下会产生相同的结果,但这意味着“获取所有作为#top 后代的div”,即,即使#top > div > div#depth2 也会被计算在内。

正如 Johannes 指出的那样,$('#top &gt; div:nth-of-type(2)') 是一个简码,但我会先熟悉基础知识 - 您可以选择带有插入符号 (>) 的类型的直接子代和带有空格 () 的类型的所有后代.

【讨论】:

  • 没问题,如果这解决了您的问题,请标记为答案。
  • 关于您对类名的评论,这是使用传统数组或.get() 比:shortcuts 更快的情况。例如,$('#top &gt; div.classname').get(n).
  • 我在对 Johannes 回复的评论中提出了另一个问题。如果您知道答案,请随时回复:)
  • 哈!打败你!
  • 打败我:D。那么 div.classname 示例是有效的吗?
【解决方案3】:
$('#top').children('div').eq(1).html()

上面的意思是;如果从 0 开始计数,则获取第二个 div,它是 top div 的子元素。

【讨论】:

    【解决方案4】:

    您可以只使用选择器 nth-of-type(number)。这是给你的

    CSS

    #top > div:nth-of-type(2) {
      /*Your css*/
    }
    

    或在 Jquery 中

    $("#top > div:nth-of-type(2)").method();
    

    顺便说一句,这是一个相同的选择器。我只是在 Jquery 选择器上使用 css nth-of-type(2) 选择器

    【讨论】:

      猜你喜欢
      • 2016-11-16
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多