jQuery-适用于所有特定类的第一个div

时间:2017-09-06 14:40:18

标签: jquery selector

我有几个元素与" .MonthAccordion"。我想对每个.MonthAccordion的第一个孩子应用一些东西,但我所拥有的似乎只是应用于第一个MonthAccordion的孩子。随后的MonthAccordions'孩子们不受影响。我在哪里?

$(".MonthAccordion").children("div:first").show();

3 个答案:

答案 0 :(得分:2)

使用.each()方法迭代所有带有'MonthAccordion'类的元素。

   $('.MonthAccordion').each(function( index ) {
      $(this).children("div:first").show();
    });

答案 1 :(得分:2)

只需选择所有直接后代,然后按第一个孩子过滤

$(".MonthAccordion > div:first-of-type").show();
.MonthAccordion > * {display:none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="MonthAccordion">
  <h4>Something else</h4>
  <div>This one</div>
  <div>Not this one</div>
</div>

<div class="MonthAccordion">
  <div>This one</div>
  <div>Not this one</div>
</div>

你的问题是jQuery first在整个集合中选择 第一个元素,而first-child选择每个父元素中的第一个元素元素等。

答案 2 :(得分:1)

使用find()方法制作它的另一种方法是,沿着DOM元素的后代向下遍历,一直到最后一个后代:

&#13;
&#13;
$(".MonthAccordion").find("div:first").show();
&#13;
.MonthAccordion > * {display:none}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="MonthAccordion">
  <div>This one</div>
  <div>Not this one</div>
</div>

<div class="MonthAccordion">
  <div>This one</div>
  <div>Not this one</div>
</div>
&#13;
&#13;
&#13;

相关问题