首页 > 解决方案 > 如何在 JQM 中删除动态添加的可折叠项

问题描述

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

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

});

谢谢

标签: jqueryjquery-mobilecollapsejquery-mobile-collapsible

解决方案


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

推荐阅读