javascript – 显示多个父div的子div

我有两个.class元素和
javascript代码,如下所示:

$(document).ready(function() {
  $(".button").click(function() {
    $(".class-sub").show();
    // how to show .class-sub by button of this parent class
  });
});
<div class="class1">
  <div>
    <a class="button">Click sub class1 class</a>
  </div>
  <br />
  <div class="class-sub" style="display:none">form class2</div>
</div>


<div class="class2">
  <div>
    <a class="button">Click sub class2 class</a>
  </div>
  <br />
  <div class="class-sub" style="display:none">form class2</div>

</div>

如何通过单击其父类的按钮来显示.class-sub?我想单击.button并显示同一父级的.class-sub.

最佳答案

$(document).ready(function() {
  $(".button").click(function() {
    $(this).parent().parent().find("div.class-sub").show();
    // how to show .class-sub by button of this parent class
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="class1">
  <div>
    <a class="button">Click sub class1 class</a>
  </div>
  <br />
  <div class="class-sub" style="display:none">form class2</div>
</div>


<div class="class2">
  <div>
    <a class="button">Click sub class2 class</a>
  </div>
  <br />
  <div class="class-sub" style="display:none">form class2</div>

</div>

使用.parent()2次到达父div并使用.find()来查找目标div

点赞