我试图在每个手风琴面板中添加一个关闭按钮。这是我的剧本。它不起作用。我哪里错了?任何帮助将不胜感激!
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
$('#close').click(function () {
$("accordion").accordion({active: false}).click();
}
}
}
&#13;
<div class="accord">
<button class="accordion"><b>one</b></button>
<div class="panel">
something about one
<div id="close"><a href="#">Close</a></div>
</div>
<button class="accordion"><b>two</b></button>
<div class="panel">
something about two
<div id="close"><a href="#">Close</a></div>
</div>
<button class="accordion"><b>three</b></button>
<div class="panel">
something about three
<div id="close"><a href="#">Close</a></div>
</div>
<button class="accordion"><b>four</b></button>
<div id="foo" class="panel">
something about four
<div id="close"><a href="#">Close</a></div>
</div>
</div>
&#13;
更新:我添加了我的HTML。希望这会让它变得更容易。提前谢谢!
答案 0 :(得分:1)
您的代码存在许多问题。首先,一个id被认为在整个html中是唯一的,所以你必须改变它来替换你的close div的id ...或者甚至更好,因为点击将在<a>
标记,您应该在这些元素上设置一个类
<div><a href="#" class="close">Close</a></div>
下一个问题是您处理点击事件的方式。你没有指定你正在使用的ui库,但我会尝试一般的解释。
//Select the close elements
$(".close").click(function() {
var closeLink = $(this);
//The root of the widget
var widget = closeLink.closest(".accord");
//This is the accordion you'll be closing
var closeAccordion = closeLink.closest(".accordion");
//The other accordion element (every acordions execpt the closing one)
var otherAccordion = widget.children(".accordion").not(closeAccordion);
//From there you can implement you logic using the variable above
});
正如您所看到的,代码已经完成,但它有助于您了解如何编写dom元素以及如何使用jquery处理它们。#/ p>