Are events lost in jQuery when you remove() an element and append() it elsewhere?

后端 未结 3 1491
隐瞒了意图╮
隐瞒了意图╮ 2021-02-18 14:35

What happens in jQuery when you remove() an element and append() it elsewhere?

It appears that the events are unhooked - as if you were just inserting fresh html (which

相关标签:
3条回答
  • 2021-02-18 15:23

    The jQuery detach() function is the same as remove() but preserves the event handlers in the object that it returns. If you have to remove the item and place it somewhere else with everything you can just use this.

    var objectWithEvents = $('#old').detach();
    $('#new').append(objectWithEvents);
    

    Check the API docs here: http://api.jquery.com/detach/

    0 讨论(0)
  • 2021-02-18 15:30

    Yes, jQuery's approach with remove() is to unbind everything bound with jQuery's own bind (to prevent memory leaks).

    However, if you just want to move something in the DOM, you don't have to remove() it first. Just append to your heart's content, the event bindings will stick around :)

    For example, paste this into your firebug on this page:

    $('li.wmd-button:eq(2)').click(function(){ alert('still here!') }).appendTo(document.body)
    

    And now scroll down to the bottom of this page and click on the little globy icon now buried under the SO footer. You will get the alert. All because I took care to not remove it first.

    0 讨论(0)
  • 2021-02-18 15:32

    use jQuery1.3.1 live() to bind events and you won't need to worry about this..

    Update: live events are deprecated now, but you can get the same effect from $(document).on().

    0 讨论(0)
提交回复
热议问题