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

早过忘川 提交于 2019-12-05 12:23:31

问题


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 I guess is what happening). But its also possible my code has a bug in it - so I just wanted to verify this behavior before I continue.

If this is the case - are there any easy ways to rehookup the events to just that portion of HTML, or a different way to move the element without losing the event in the first place.


回答1:


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.




回答2:


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/




回答3:


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().



来源:https://stackoverflow.com/questions/559147/are-events-lost-in-jquery-when-you-remove-an-element-and-append-it-elsewhere

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!