OnClick函数需要只打开子元素

时间:2016-11-15 15:46:35

标签: javascript jquery html

嗨,这是我的HTML代码:

<div class="title-of-theme">
     <img class="plus-minus-sign theme-sign" src="images/plus-sign.png" alt="">  <h3>Theme</h3>
</div>
<div class="title-of-question">
     <img class="plus-minus-sign2" src="images/plus-sign.png" alt=""><h4>Question —›</h4>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci blanditiis cumque earum incidunt inventore maiores natus sit tempore? Nisi, sequi.</p>
</div>

我的JS代码:

$('.plus-minus-sign, h3').on('click', function () {
   $('.title-of-question').toggleClass('show-menu');
});
$('.plus-minus-sign2, h4').on('click', function () {
   $('.faq p').toggleClass('show-menu');
});

因为我将拥有许多h3标题和段落,并且那些段落和标题都具有相同的类我需要做的事情当我点击一个h3时它应该只打开他的子元素 但现在当我点击一个h3时,它会打开所有元素

1 个答案:

答案 0 :(得分:0)

您需要使用点击元素中的DOM遍历,您可以使用事件处理程序中的this关键字来查找,以查找切换类所需的元素。试试这个:

$('.plus-minus-sign, h3').on('click', function() {
  $(this).closest('.title-of-theme').next('.title-of-question').toggleClass('show-menu');
});
$('.plus-minus-sign2, h4').on('click', function() {
  $(this).closest('.title-of-question').find('p').toggleClass('show-menu');
});
.show-menu { border: 1px solid #c00; } /* for demo only */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title-of-theme">
  <img class="plus-minus-sign theme-sign" src="images/plus-sign.png" alt="">
  <h3>Theme</h3>
</div>
<div class="title-of-question">
  <img class="plus-minus-sign2" src="images/plus-sign.png" alt="">
  <h4>Question —›</h4>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci blanditiis cumque earum incidunt inventore maiores natus sit tempore? Nisi, sequi.</p>
</div>

<div class="title-of-theme">
  <img class="plus-minus-sign theme-sign" src="images/plus-sign.png" alt="">
  <h3>Theme</h3>
</div>
<div class="title-of-question">
  <img class="plus-minus-sign2" src="images/plus-sign.png" alt="">
  <h4>Question —›</h4>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Adipisci blanditiis cumque earum incidunt inventore maiores natus sit tempore? Nisi, sequi.</p>
</div>