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

Events attached to Jquery object not triggered on re-insert into DOM

我创建了一个 jQuery 对象:

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

并附上一些活动:

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

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

$(document).html($el);

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

$(document).html($another_el);

然后改回来

$(document).html($el);

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

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

来自 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.

http://api.jquery.com/html/#html-htmlString

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.