gpt4 book ai didi

javascript - jquery-ui accordion - 如何动态创建一个新的部分

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:58:25 25 4
gpt4 key购买 nike

我想知道是否存在可以使用 jQuery UI 添加新部分的方法

这是我到目前为止所做的,没有任何错误,但是 Accordion 不工作,因为我添加了一个新的

$( function() {
$( "#accordion" ).accordion();

$('#addNewSection').on('click', function() {
var newH3 = document.createElement('h3');
var newDiv = document.createElement('div');
var acc = document.getElementById('accordion');
var number = document.getElementsByTagName('h3').length;

newH3.innerText = 'Section' + (parseInt(number) + 1) + "(This won't collapse)";
newDiv.innerText = 'This is a new section after clicking the button';
acc.appendChild(newH3);
acc.appendChild(newDiv);
});
} );
h3 { background-color: "blue"; }
div { background-color: "lightgreen"; }
<div id="accordion">
<h3>Section 1 (collapsible)</h3>
<div>
<p>
This is the context in section 1
</p>
</div>

<h3>Section 2 (collapsible)</h3>
<div>
<p>
This is the context in section 2
</p>
</div>
</div>
<button id="addNewSection">AddOne</button>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

如何解决?或者有什么官方方法可以使用吗?

最佳答案

您可以在点击事件 (Documentation) 结束时使用 Accordion 的 refresh 方法:

$( function() {
$( "#accordion" ).accordion();

$('#addNewSection').on('click', function() {
var newH3 = document.createElement('h3');
var newDiv = document.createElement('div');
var acc = document.getElementById('accordion');
var number = document.getElementsByTagName('h3').length;

newH3.innerText = 'Section' + (parseInt(number) + 1) + "(This WILL collapse)";
newDiv.innerText = 'This is a new section after clicking the button';
acc.appendChild(newH3);
acc.appendChild(newDiv);
$( "#accordion" ).accordion("refresh");
});
} );
h3 { background-color: "blue"; }
div { background-color: "lightgreen"; }
<div id="accordion">
<h3>Section 1 (collapsible)</h3>
<div>
<p>
This is the context in section 1
</p>
</div>

<h3>Section 2 (collapsible)</h3>
<div>
<p>
This is the context in section 2
</p>
</div>
</div>
<button id="addNewSection">AddOne</button>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

关于javascript - jquery-ui accordion - 如何动态创建一个新的部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48075295/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com