网页最初会有一个按钮。单击它后,它会添加两个手风琴,这些手风琴的标题存储在列表中,这是点击事件处理功能的一部分。该按钮应该创建从同一列表中读取的新手风琴,而不管它被点击的次数。
<script>
$(function() {
$("#updateAccordion").click(function() {
new_array = ['new_item1', 'new_item2']
$("#mainAccordion").empty();
var accordion_data = ''
for (var i = 0; i < new_array.length; i++) {
accordion_data += '<h3><a href="#">' + new_array[i] + '</a></h3><div class="accordion">'
accordion_data += '</div>'
}
$("#mainAccordion").append(accordion_data)
$(".accordion").accordion({
heightStyle: 'content',
active: false,
collapsible: true
});
});
});
</script>
<button id="updateAccordion">Apply</button>
<div class="accordion" id="mainAccordion">
</div>
这是第一次按预期工作。但是,再次单击它时,它不会创建任何手风琴。它只是为链接创建。
可以找到小提琴here。
答案 0 :(得分:0)
您的计划中发现了几个问题。
;
放在表达式的末尾.e var accordion_data = ''
。jquery.js
,jquery-ui.js
和jquery-ui.css
这些图书馆。请遵循以下代码,这非常有效。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script type="text/javascript">
$(function(){
$('#mainAccordion').accordion({
heightStyle: 'content',
active: false,
collapsible: true
});
});
$(function(){
$("#updateAccordion").click(function() {
var new_array = ['new_item1', 'new_item2'];
$("#mainAccordion").empty();
var accordion_data = '';
for (var i = 0; i < new_array.length; i++) {
accordion_data += '<h3><a href="#">' + new_array[i] + '</a></h3><div class="accordion"><p>this is some text</p></div>';
}
var option = {
heightStyle: 'content',
active: false,
collapsible: true
};
$("#mainAccordion").append(accordion_data);
$("#mainAccordion").accordion('destroy').accordion(option);
});
});
</script>
<button id="updateAccordion">Apply</button>
<div id="mainAccordion" class="accordion">
<h3><a href="#">Section 1</a></h3>
<div>
<p>Section 1 Content</p>
</div>
<h3><a href="#">Section 2</a></h3>
<div>
<p>Section 2 Content
</div>
<h3><a href="#">Section 3</a></h3>
<div>
<p>Section 3 Content</p>
</div>
<h3><a href="#">Section 4</a></h3>
<div>
<p>Section 4 Content</p>
</div>
</div>
&#13;