现在我可以点击标题,然后在所有容器上切换类。我需要它做的是当我再次点击标题时切换课程。
任何人都可以帮忙吗?
$('.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>
答案 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");
});
$('.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;
答案 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>