JQuery追加到父级,只要它's已创建

JQuery Appending to the parent, as soon as it's created

本文关键字:创建 追加 JQuery      更新时间:2023-09-26

我想在创建e后立即使用$(e).append()

我知道我可以用setTimeout(/*func checking if parent exists*/, 100),但我觉得这真的是个坏主意。是否存在某种DOM事件,当修改DOM元素的子树时会触发该事件?

我通常只会把它粘贴在源代码中,粘贴到创建父级的函数中,但这实际上是不可能的,部分原因是我实际上正在制作Chrome扩展。

感谢您的帮助

我会使用这个库来等待元素的存在Arrive.js

// watch for creation of an element which satisfies the selector ".test-elem"
$(document).arrive(".test-elem", function() {
    // 'this' refers to the newly created element
    var $newElem = $(this);
});
// the above event would watch for creation of element in whole document
// it's better to be more specific whenever possible, for example
$(".container-1").arrive(".test-elem", function() {
    var $newElem = $(this);
});

正如你所看到的,它真的很容易使用。如果您不想使用外部库,则需要查看JS中的MutationObserver,因为DOMNodeInserted已折旧。

如文档所示,很容易解除库的绑定:

// unbind all arrive events on document element
$(document).unbindArrive();
// unbind all arrive events on document element which are watching for ".test-elem" selector
$(document).unbindArrive(".test-elem");
// unbind only a specific callback
$(document).unbindArrive(callbackFunc);
// unbind only a specific callback on ".test-elem" selector
$(document).unbindArrive(".test-elem", callbackFunc);
// unbind all arrive events
Arrive.unbindAllArrive();

如果e是某些静态HTML的一部分,则可以使用典型的:

$(document).ready(function(){
    //code here
}

如果e是由代码动态添加的,则可以使用DOMNodeInserted事件。为了这个例子,我假设e<li>

$(document).on('DOMNodeInserted', 'li', function(){
   //code here
});