gpt4 book ai didi

javascript - 附加到 Jquery 对象的事件在重新插入 DOM 时未触发

转载 作者:行者123 更新时间:2023-11-30 17:02:43 25 4
gpt4 key购买 nike

我创建了一个 jQuery 对象:

var $el = $("<div>");

并附上一些事件:

$el.on(event, selector, callback);

然后我添加最终会触发这些事件的内部 html。然后我将 $el 添加到文档中:

$(document).html($el);

所有事件都按预期触发。但是当我更改文档的内容时:

$(document).html($another_el);

然后改回来

$(document).html($el);

那些相同的事件不再被触发。我是否遗漏了一些明显的东西?

最佳答案

如果您想保留附加的 JQuery 数据(例如事件处理程序),您应该在通过 html() 分配新元素之前显式地 detach() 元素。

来自 jQuery 文档:

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.

The .detach() method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

关于javascript - 附加到 Jquery 对象的事件在重新插入 DOM 时未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28545793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com