简体   繁体   English

当您 remove() 一个元素并在其他地方 append() 它时,jQuery 中的事件会丢失吗?

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

What happens in jQuery when you remove() an element and append() it elsewhere?当你remove()一个元素并append()它在别处时,jQuery 会发生什么?

It appears that the events are unhooked - as if you were just inserting fresh html (which I guess is what happening).似乎这些事件没有挂钩 - 好像您只是插入新的 html(我猜这就是发生的事情)。 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.如果是这种情况 - 是否有任何简单的方法可以将事件重新连接到 HTML 的那部分,或者有一种不同的方法来移动元素而不会首先丢失事件。

The jQuery detach() function is the same as remove() but preserves the event handlers in the object that it returns. jQuery detach()函数与remove()相同,但在它返回的对象中保留了事件处理程序。 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/在此处查看 API 文档:http: //api.jquery.com/detach/

Yes, jQuery's approach with remove() is to unbind everything bound with jQuery's own bind (to prevent memory leaks).是的,jQuery 使用remove()的方法是取消绑定与 jQuery 自己的bind绑定的所有内容(以防止内存泄漏)。

However, if you just want to move something in the DOM, you don't have to remove() it first.但是,如果您只想在 DOM 中移动某些内容,则不必先remove()它。 Just append to your heart's content, the event bindings will stick around :)只需append到您心中的内容,事件绑定就会一直存在:)

For example, paste this into your firebug on this page:例如,将其粘贴到此页面上的 firebug 中:

$('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.现在向下滚动到此页面的底部,然后单击现在埋在 SO 页脚下的小地球图标。 You will get the alert .您将收到alert All because I took care to not remove it first.这一切都是因为我注意不要先remove它。

use jQuery1.3.1 live() to bind events and you won't need to worry about this..使用 jQuery1.3.1 live() 绑定事件,你不必担心这个..

Update: live events are deprecated now, but you can get the same effect from $(document).on().更新:现在不推荐使用实时事件,但您可以从 $(document).on() 获得相同的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM