【问题标题】:Separate appends with same remove method not working使用相同的删除方法单独附加不起作用
【发布时间】:2014-02-23 00:34:51
【问题描述】:

所以基本上我在一个表中添加了两个不同的东西,使用相同的 .parent().parent().remove() 方法,在第一个表中它可以工作,在第二个表中它没有。

有什么想法吗?

这里是代码。 http://jsfiddle.net/rzmA4/

 $(document).ready(function(){
      $('#adauga_model').on('click', function(){
           $('#modele_adaugate').append('<tr><td><input type="file" name="model[]"></td><td><button class="remove" type="button">Remove</button></td></tr>');
      });
      $('#adauga_design').on('click', function(){
           $('#designuri_adaugate').append('<tr><td><input type="file" name="design[]"></td><td><button class="remove" type="button">Remove2</button></td></tr>');
      });
      $("td").on('click', '.remove', function() {
           $(this).parent().parent().remove();
           return false;
      });
 });

【问题讨论】:

    标签: javascript jquery html appendchild removechild


    【解决方案1】:

    有趣的是,它完全可以在第一个上运行,但是当文档加载时,您正在为所有 TD 元素添加一个事件侦听器。但是,您正在创建新的,没有事件监听器。

    为了解决问题,我重写了如下脚本:

     $("body").on('click', 'td .remove', function() {
          $(this).closest("tr").remove();
          return false;
     });
    

    作为奖励:使用closest("tr") 比使用parent().parent() 更好。当您执行后者并且稍后更改您的设计时,您可能会遇到错误。

    【讨论】:

      猜你喜欢
      • 2014-02-18
      • 2018-12-22
      • 2016-08-30
      • 1970-01-01
      • 2014-12-25
      • 1970-01-01
      • 2013-06-03
      • 2012-10-26
      • 1970-01-01
      相关资源
      最近更新 更多