【问题标题】:Remove dynamically generated <div> on click点击时删除动态生成的 <div>
【发布时间】:2013-02-17 03:48:01
【问题描述】:

我在点击&lt;div&gt; 时尝试它。当我尝试使用 .live() 时,它向我显示:

对象没有方法 live()

我使用的是 jQuery 版本 1.9,所以 live 已被删除。

$(document).ready(function(){
    $('#addhelper').click(function(){
        $('div#containerr').append('<div class ="helpcont"><input type="text" name="helper_caption[]" class="input-large" placeholder="Caption">'+
      '<input type="text" name="helper_url" class="input-large" placeholder="Url">'+
      '<input type="text" name = "helper_source" class="input-large" placeholder="Source"><button class = "remove" type="button">remove</button></div>');
    });

    $("button.remove").on({
        click: function(){
            $(this).remove('div.helpcont');
        }
    });
});

【问题讨论】:

标签: javascript jquery event-delegation


【解决方案1】:
$("#containerr").on('click', '.remove', function(){
  $(this).closest('.helpcont').remove();
});

#containerr = 动态添加的最近父级

click = 事件(可以添加多个事件,用空格分隔)

.remove = 触发事件的选择器


PS:使用 #id 之类的选择器,而不是 element#id。无论如何,ID 都应该是唯一的,因此无需采用缓慢的方式,让 jQuery 检索所有 DIV 元素,然后搜索具有给定 ID 的元素。

【讨论】:

  • $("button.remove").on('click', function(){ $(this).parent('.helpcont').remove(); }); 连这个也不行
  • @pony 你能简单解释一下这行吗?$("div#containerr").on('click', '.remove', function()
猜你喜欢
  • 2015-05-19
  • 1970-01-01
  • 2015-05-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-20
  • 2012-10-10
  • 1970-01-01
  • 2014-08-20
相关资源
最近更新 更多