我正在尝试使用这个 jQuery Mobile 可折叠“添加”按钮,在多次点击或添加如此多的 div 等后停止。
就目前情况而言,它只会增加无限量。
这来自演示文档 http://demos.jquerymobile.com/1.4.1/collapsible-dynamic/
<button type="button" data-icon="gear" data-iconpos="right" data-mini="true" data-inline="true" id="add">Add</button>
<button type="button" data-icon="plus" data-iconpos="right" data-mini="true" data-inline="true" id="expand">Expand last</button>
<button type="button" data-icon="minus" data-iconpos="right" data-mini="true" data-inline="true" id="collapse">Collapse last</button>
<div data-role="collapsibleset" data-content-theme="a" data-iconpos="right" id="set">
<div data-role="collapsible" id="set1" data-collapsed="true">
<h3>Section 1</h3>
<p>I'm the collapsible content.</p>
</div>
</div>
JS
$( document ).on( "pagecreate", function() {
var nextId = 1;
$("#add").click(function() {
nextId++;
var content = "<div data-role='collapsible' id='set" + nextId + "'><h3>Section " + nextId + "</h3><p>I am the collapsible content in a set so this feels like an accordion. I am hidden by default because I have the 'collapsed' state; you need to expand the header to see me.</p></div>";
$( "#set" ).append( content ).collapsibleset( "refresh" );
});
$( "#expand" ).click(function() {
$("#set").children(":last").collapsible( "expand" );
});
$( "#collapse" ).click(function() {
$( "#set" ).children( ":last" ).collapsible( "collapse" );
});
});
最佳答案
在添加按钮处理程序中,只需计算当前可折叠 div 的数量($('#set [data-role="collapsible"]').length
),如果您的最大值为已经向用户发送消息并退出该功能:
$("#add").click(function() {
var curNumOfDivs = $('#set [data-role="collapsible"]').length;
if (curNumOfDivs > 4){
alert("You have exceeded tha max allowed collapsibles!");
return false;
}
nextId++;
var content = "<div data-role='collapsible' id='set" + nextId + "'><h3>Section " + nextId + "</h3><p>I am the collapsible content in a set so this feels like an accordion. I am hidden by default because I have the 'collapsed' state; you need to expand the header to see me.</p></div>";
$( "#set" ).append( content ).collapsibleset( "refresh" );
});
Working DEMO
关于javascript - jQuery Mobile - 动态可折叠在一定数量后停止添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25754000/