单击按钮时如何切换所有div

时间:2017-01-12 23:07:13

标签: javascript jquery html toggle show-hide

需要关闭(隐藏)所有.body divs =? (div.body {display:none}?)

需要关闭(隐藏)所有.body打开div,点击.button

需要打开最近的.body div,点击.button

时打开 单击.button

时,

需要更改.button图标(负图标或正图标)

HTML

<div class="box">

  <div class="header">

    <a href="#" class="button">

      <span class="fa positive"></span>

    </a>

  </div>

  <div class="body">

  </div>

</div>

JQUERY

jQuery('.button').on('click', function() {

  jQuery('.body').close();

  jQuery(this).closest(".body, .header").toggle(); // Edit 

  jQuery('span').toggleClass('negative');

  jQuery(this).parents().find('.body').toggle() // i test it, doesn't work

});

风格

.body {
  display:none;
}

.button .positive:before {
  content : "sample ( + )";
}

.button .negative:before {
  content : 'sample ( - )';
}

enter image description here

1 个答案:

答案 0 :(得分:2)

这样可行:

$('.button').on('click', function() {
  $btn = $(this);
  $('.body').hide();
  $('.box .negative').removeClass('negative').addClass('positive');

  $btn.closest('.box').find('.body').toggle(); 
  $btn.find('span').toggleClass('negative');

});
.body {
  display:none;
}

.button .positive:before {
  content : "sample ( + )";
}

.button .negative:before {
  content : 'sample ( - )';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box"> 
  <div class="header"> 
    <a href="#" class="button">
      <span class="fa positive"></span>
    </a>
  </div>
  <div class="body">
   some text
  </div>
</div>

<div class="box">
  <div class="header">
    <a href="#" class="button">
      <span class="fa positive"></span>
    </a>
  </div>
  <div class="body">
   some text
  </div>
</div>