【问题标题】:Why does jquery not remove an appened div为什么 jquery 不删除附加的 div
【发布时间】:2014-01-03 17:46:37
【问题描述】:

我在表单中有字段并允许用户添加或删除项目。第一个附加的突出显示会删除,但任何添加的突出显示都不会删除。

我尝试了以下方法,但没有运气jQuery $(this).remove() not working after append

这是http://jsfiddle.net/3PzmH/3/下面代码的jsfiddle

<!-- html -->
<div class="features"></div>

// js
var highlight = '<div class="form-group"><label for="highlight" class="col-sm-3 col-lg-2 control-label">Hightlight:</label><div class="col-sm-9 col-lg-3 controls"><input type="text" name="highlight_name[]" data-rule-required="true" class="form-control" value="Hightlight Name"></div><div class="col-sm-9 col-lg-7 controls"><textarea name="highlight_description[]" class="form-control" rows="3" placeholder="Description for highlight"></textarea><a href="" class="pull-right showhouse-text remove_highlight"><i class="fa fa-plus"></i> Remove Highlight</a></div></div>';
$('.features').append(highlight);

$('#add_highlight').click(function(){
    $('.features').append(highlight);
});

$('.remove_highlight').on("click", function(){
    $(this).closest('.form-group').remove();
});

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    将事件委托给静态父元素

    $('.features').on("click", '.remove_highlight', function(){
        $(this).closest('.form-group').remove();
    });
    

    FIDDLE

    【讨论】:

      【解决方案2】:

      动态添加的元素需要使用事件委托

      $('.features').on("click",'.remove_highlight', function(){
          $(this).closest('.form-group').remove();
      });
      

      DEMO

      【讨论】:

        【解决方案3】:

        因为动态添加的元素没有绑定任何函数。

        使用事件委托

        $('.features').on('click', '.remove_highlight', function() {
            $(this).closest('.form-group').remove();
        });
        

        【讨论】:

          【解决方案4】:

          请使用委托。请参阅更新的小提琴。

          http://jsfiddle.net/3PzmH/7/

          $(document).delegate('.remove_highlight',"click", function(){
              $(this).closest('.form-group').remove();
          });
          

          【讨论】:

          • 取决于 jQuery 版本,这可能不是最好的方法,请参见此处:api.jquery.com/delegate "从 jQuery 1.7 开始,.delegate() 已被 .on() 方法取代。对于早期版本,但是,它仍然是使用事件委托的最有效方法。有关事件绑定和委托的更多信息在 .on() 方法中。"
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-05-26
          • 1970-01-01
          • 2017-08-06
          • 2017-04-11
          • 1970-01-01
          相关资源
          最近更新 更多