jQuery Mobile - 动态可折叠在一定数量后停止添加

时间:2014-09-09 21:43:34

标签: javascript php jquery jquery-mobile mobile

我正在尝试使用这个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" );
});
});

1 个答案:

答案 0 :(得分:1)

在添加按钮处理程序中,只计算当前可折叠div($('#set [data-role="collapsible"]').length)的数量,如果你的max已经存在,则向用户发送消息并退出该函数:

$("#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" );
});
  

正在使用 DEMO