首页 > 解决方案 > 如何使用可编辑的 HTML 页面和不同级别的用户添加元素来更新 javascript

问题描述

编辑:对于一般解决方案,这对我有用。动态创建元素的事件绑定?

所以我有一个看起来像这样的界面:

默认

用户可以切换以显示或隐藏子列表。我使用 jquery 来选择切换按钮以使其工作:

$(".dropdownBtn").click(function(){
  //rotate the button
  $(this).parent().toggleClass("caret-down");
  //hide the sublist
  $(this).closest("li").find(".active").toggleClass("nested");
})

他们还可以为每个元素添加新的 sub_elements。例如,像这样:

更新

$(".fa-plus-square").click(function(){
//if there's no new list, create a new unordered list
  if ($(this).closest("li").find("ul").length == 0){
    $(this).parents("li").append(newUL);
    //and add a toggle button
    $(this).parent().prepend(toggleBtn);
  }
  //add the element
  $(this).closest("li").find("ul").append("<li>newElement</li>")
})

但是随后元素 3 下新添加的切换按钮不会响应。我相信我需要“绑定”新添加的按钮。但我不确定这样做的最佳做法是什么。

标签: javascripthtmljquery

解决方案


推荐阅读