单击容器上的toggleClass并删除其他容器上的相同类

时间:2017-04-19 11:27:07

标签: jquery

现在我可以点击标题,然后在所有容器上切换类。我需要它做的是当我再次点击标题时切换课程。

任何人都可以帮忙吗?

$('.title').click(function() {
  $('.container').removeClass('open');
  $(this).parents('.container').toggleClass("open");
});
.content {
  display: none;
}

.open .content {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="title">
    title
  </div>
  <div class="content">
    content goes here
  </div>
</div>
<div class="container">
  <div class="title">
    title 2
  </div>
  <div class="content">
    content goes here 2
  </div>
</div>

2 个答案:

答案 0 :(得分:1)

使用removeClass()

时,您需要排除父容器
$('.title').click(function() {
  //Get the reference of parent container
  var parentContainer = $(this).parents('.container');

  //Remove open class except from parentContainer
  $('.container').not(parentContainer).removeClass('open');

  //Toggle class on parentContainer
  parentContainer.toggleClass("open");
});

&#13;
&#13;
$('.title').click(function() {
  var parentContainer = $(this).parents('.container');
  $('.container').not(parentContainer).removeClass('open');
  parentContainer.toggleClass("open");
});
&#13;
.content {
  display: none;
}

.open .content {
  display: block;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="title">
    title
  </div>
  <div class="content">
    content goes here
  </div>
</div>
<div class="container">
  <div class="title">
    title 2
  </div>
  <div class="content">
    content goes here 2
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

你可以在jquery中使用.not(this),请查看我的片段

$('.title').click(function() {
  $('.container').not(this).removeClass('open');
  $(this).parents('.container').toggleClass("open");
});
.content {
  display: none;
}

.open .content {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="title">
    title
  </div>
  <div class="content">
    content goes here
  </div>
</div>
<div class="container">
  <div class="title">
    title 2
  </div>
  <div class="content">
    content goes here 2
  </div>
</div>