JQuery追加到父级,只要它's已创建
JQuery Appending to the parent, as soon as it's created
我想在创建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
});
相关文章:
- JQuery追加到父级,只要它's已创建
- 在函数中定位动态创建的HTML元素(用于追加事件 - 而不是点击!)jQuery
- 如何在追加函数创建后最小化单个框
- 追加子节点创建一个新节点
- 确保追加的行始终是表中由动态创建的行组成的最后一行..detach().
- 在jquery中使用追加创建文本框和按钮(我得到重复的结果)
- 创建/追加 HTML 元素(浏览器内存)
- 如何在 aspx 页中创建定位点或追加项
- JQuery 不知不觉地追加了创建的 JQuery 对象
- 如何知道Mongoose'的追加销售创建了一个新文档
- d3创建对象而不追加
- JQuery中动态创建的元素不断追加到DOM
- 在类创建/追加时增加计数器的值1
- 创建/追加包含包含引号的blob文本的元素
- Iframe追加创建一个副本
- 创建和追加一个元素,innerHTML?恐怖. .[请不要使用jquery]
- 通过首先从HTML页面的值创建文本文件来追加/编辑文本文件
- 动态创建的下拉多个追加不能工作
- 如何动态创建和追加DIV
- 在javascript中创建数组并在闭包内追加值