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

标签 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" );
});
});

最佳答案

在添加按钮处理程序中,只需计算当前可折叠 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/

相关文章:

javascript - 如何为玩家分配一个 2 位数的唯一 ID

php - 使用 Zend Framework 从 1and1 smtp 服务器发送电子邮件

php - Codeigniter 数据库结果 - 对象还是数组?

javascript - 尝试使用 Jquery 制作动画时 Div 更改到错误位置

javascript - 当页面上的所有按钮都具有相同的 CSS 类时,如何依次单击它们(开发控制台脚本)

javascript:添加和删除表格行,无法获得正确的编号

php - 单击图像时如何更改样式表

php - 将 mysql db(带数字的数据)导出到 csv

javascript - 如何在没有路径问题的情况下在母版页 header 中包含 jquery?

当窗口大小增加时,jQuery 移动菜单不会消失