【问题标题】:Deleting a dynamically added div on a parent causes it to append again删除父级上动态添加的 div 会导致它再次追加
【发布时间】:2014-07-22 20:05:10
【问题描述】:

JsFiddle

我正在尝试在单击 td.active 时动态添加一个 div。我希望在有人点击关闭按钮或点击其他td.active时删除动态添加的div

现在我的代码只是在单击关闭按钮时附加另一个 div。谁能帮我解决这个问题。

$(function() {
    $('td.active').click(function(event){
        $(this).append('<div class="planner-modal"><div class="planner-modal-header"><button type="button" class="close"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button><h5 class="text-center">modal heading</h5></div><div class="planner-modal-body">modal body</div><div class="caret-container"><div class="top-caret"></div><div class="bottom-caret"></div></div></div>');
    });
    $('.planner-modal-header.close').click(function(e){
        $(this).closest('planner-modal').remove();
    });
});

【问题讨论】:

  • 我想你忘了把点“。”在最接近('planner-modal')。尝试最接近('.planner-modal')
  • @exculuber 谢谢。试过了。也没有用。
  • 把 $('.planner-modal-header.close').click(function(e){ $(this).closest('.planner-modal').remove(); });在 td.active 点击函数内
  • 没有用。 jsfiddle.net/daL6s/12

标签: javascript jquery


【解决方案1】:

我已经完成了 jsfiddle 并修复了它。您试图在动态添加的内容上调用 click 事件,我们可以使用 jQuery on 方法。 我正在分享 jsfiddle 链接。

  $(document).on("click",'.close',function(e){

      $('.planner-modal').remove()
    });

click here to see the working jsfiddle example

谢谢

【讨论】:

  • 如果应该同时打开一个计划器模式,这可能会起作用。但是,您应该将 $('.planner-modal').remove() 插入到 td.active 点击函数的开头
  • 我想我已经在 td.active 的点击功能中通过 jsfiddle 链接做到了这一点..:) 谢谢
【解决方案2】:

对动态创建的元素使用事件委托

  $('td.active').on("click", ".planner-modal-header .close", function (e) {
    e.stopPropagation(); 
    $(this).closest('.planner-modal').remove();
});

DEMO

使用e.stopPropagation(); 停止bubbling event

【讨论】:

  • @Bala 你能看到我的小提琴并修复它吗
  • @Bala 我想你忘了提到 e.stopPropagation()
  • @user2847429 现在查看演示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多