如何删除JQM中动态添加的可折叠

时间:2018-11-03 08:21:14

标签: jquery jquery-mobile collapse jquery-mobile-collapsible

我正在使用Jquery Mobile的参考来构建UI,但是在Jquery Mobile演示中给出的示例中陷入了如何删除动态添加的可折叠对象的想法。

http://demos.jquerymobile.com/1.4.5/collapsible-dynamic/

我已经生成了一个示例。 JSBIN

使用了JS:

console.log("DOM Load");
$( document ).on( "pagecreate", function() {
    var nextId = 1;
    $("#add").click(function() {
    nextId++;
      var content = "";
    content += "<div data-role='collapsible' id='set" + nextId + "'>";
    content += "<h3>Section " + nextId + "</h3>";
    content += "<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>";
    content += "<button id='removeStyle" + nextId + "' class='removeStyleBtn ui-btn ui-btn-b ui-shadow ui-corner-all ui-mini'>Remove</button></div>";

    $( "#set" ).append( content ).collapsibleset( "refresh" );
    //$("#set" + nextId+ " :button").button().button('refresh');
    $("#set" + nextId).collapsible( "expand" );
    console.log("collapsible set " + nextId + " added !!!");
  });
  console.log("pagecreate triggered !!!");

  $(".removeStyleBtn").click(function() {
    console.log("Removed Element !!!!!");
  });

});

谢谢

2 个答案:

答案 0 :(得分:1)

jQuery Mobile正在增强您页面中的标记,但是您甚至不需要完全了解增强的DOM-Tree层次结构。在提供的演示中,您需要搜索collapsible按钮上方的第一个Remove

在这里:

$(document).on("vclick", ".removeStyleBtn", function() {
  var parentCollapsible = $(this).closest('div[data-role="collapsible"]');
  var parentCollapsibleSet = $(parentCollapsible).closest('div[data-role="collapsibleset"]');
  $(parentCollapsible).collapsible("destroy");
  $(parentCollapsible).remove();
  $(parentCollapsibleSet).collapsibleset("refresh");
});

顺便说一句,我建议您也仅针对包含可折叠集的页面(或使用pagecreate语句)过滤switch事件,否则-如果您有多个页面-该代码将被执行多次。在您的示例中,如下所示:

标记:

<div data-role="page" id="page-with-collapsible">

JS:

$(document).on("pagecreate", "#page-with-collapsible", function() {
  var nextId = 1;
  $("#add").click(function() {
    nextId++;
    var content = "";
    content += "<div data-role='collapsible' id='set" + nextId + "'>";
    content += "<h3>Section " + nextId + "</h3>";
    content += "<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>";
    content += "<button id='removeStyle" + nextId + "' class='removeStyleBtn ui-btn ui-btn-b ui-shadow ui-corner-all ui-mini'>Remove</button></div>";
    $("#set").append(content).collapsibleset("refresh");
    $("#set" + nextId).collapsible("expand");
    console.log("collapsible set " + nextId + " added !!!");
  });
});

答案 1 :(得分:0)

id每个元素必须唯一,因此请删除按钮id(在您的情况下不需要)

然后执行:-

$(document).on("click",".removeStyleBtn",function() {
    $(this).closest('div[data-role="collapsible"]').remove();
});

将此代码放在$(document).ready(){..});之外

输出:-https://jsbin.com/vuyehocate/edit?html,js