【问题标题】:Deleting a cloned div删除克隆的 div
【发布时间】:2012-01-11 16:13:18
【问题描述】:
<div class="transactionsWrapper">
  <input type="button" value="Delete" />
</div>

如果我将上面的 div 克隆了 5 次,根据单击的删除按钮删除 div 的 jquery 代码是什么?

【问题讨论】:

    标签: jquery html button clone


    【解决方案1】:
    $( ".transactionsWrapper input:button" ).click( function() {
        $( this ).parent().remove();
    } );
    

    【讨论】:

      【解决方案2】:

      这应该可行:

      $('input:button[value="Delete"]').click(function() {
          $(this).closest('div.transactionsWrapper').remove();
      });
      

      【讨论】:

        【解决方案3】:
        $(document).on('click', '.transactionsWrapper button', function(){
            $(this).parent().remove();
        })
        

        【讨论】:

        • 如果jQuery版本低于1.7,只需将on函数替换为delegate即可。
        【解决方案4】:
        $(".button").click(function(){
            if($(this).parent().hasClass("transactionsWrapper")){
                $(this).parent().remove();
            }
        })
        

        【讨论】:

          【解决方案5】:

          只是...删除输入的父级?

          $('input[value=Delete]').on('click', function () {
              $(this).parent().remove();
          });
          

          编辑

          嗯...如果您在分配事件侦听器之后添加克隆的&lt;div&gt; 元素,这将不起作用。最安全的方法是使用委托:

          $(document.body).on('click', 'input[value=Delete]', function () {
              $(this).parent().remove();
          });
          

          【讨论】:

          • @Ben 这是对早期版本答案的评论吗?因为,就目前而言,它看起来和你的答案一模一样。
          • 是的,那是关于旧版本的。
          猜你喜欢
          • 1970-01-01
          • 2012-12-02
          • 1970-01-01
          • 2018-03-03
          • 1970-01-01
          • 1970-01-01
          • 2017-05-01
          • 1970-01-01
          • 2012-05-07
          相关资源
          最近更新 更多