我的任务是在不使用现有示例的情况下创建简单的手风琴。这个想法并不新鲜。 DOM中有title
和description
个元素。点击标题后,描述打开。再次单击此标题关闭说明。单击另一个标题关闭打开的描述并打开已单击的标题说明。所以我写下一个代码,通过点击标题打开描述,点击另一个标题时关闭它并打开相关描述。但是有下一个问题。我点击标题并打开说明。我再次点击这个标题,但描述并未关闭。
这是我的DOM:
(function($) {
$(function() {
var $title = $('.accordion .title');
var $desc = $('.desc');
var activateClass = 'active';
function accordion() {
$title.click(function() {
$this = $(this);
if ($desc.hasClass(activateClass)) {
$desc.removeClass(activateClass);
}
if ($this.next().hasClass(activeClass)) {
$this.next().removeClass(activeClass)
} else {
$this.next().addClass();
}
});
}
accordion();
});
})(jQuery);

ul {
list-style: none;
}
ul li.title {
border: 1px solid #0F0F0F;
background: #CCCCCC;
font-size: 1.4rem;
margin: 0 10px 0px 10px;
padding: 6px 8px;
}
ul li.desc {
display: none;
font-size: 1.2rem;
padding: 8px 16px;
text-align: justify;
}
ul li.active {
display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="accordion">
<li class="title">Title-1</li>
<li class="desc">Description-1
<li class="title">Title-2</li>
<li class="desc">Description-2</li>
</ul>
&#13;
答案 0 :(得分:0)
您的代码出错undefined activeClass
请始终关注控制台错误..而不是所有检查类,您只能使用两行代码
$('.desc').not($this.next('.desc')).removeClass('active'); // remove active class from all desc elements but not the one which next to the title you click
$this.next('.desc').toggleClass('active'); // toggleClass active to desc next to the title clicked
工作示例
$(function() {
var $title = $('.accordion .title');
var $desc = $('.desc');
function accordion() {
$title.click(function() {
$this = $(this);
$desc.not($this.next('.desc')).removeClass('active');
$this.next('.desc').toggleClass('active');
});
}
accordion();
});
ul {
list-style: none;
}
ul li.title {
border: 1px solid #0F0F0F;
background: #CCCCCC;
font-size: 1.4rem;
margin: 0 10px 0px 10px;
padding: 6px 8px;
}
ul li.desc {
display: none;
font-size: 1.2rem;
padding: 8px 16px;
text-align: justify;
}
ul li.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="accordion">
<li class="title">Title-1</li>
<li class="desc">Description-1
<li class="title">Title-2</li>
<li class="desc">Description-2</li>
</ul>