我正在寻找这样的东西:
var div = document.createElement('div');
div.id = 'proprioceptiveDiv';
$(div).on('appendedToDOM', function() {
// ...
});
document.body.appendChild(div); // triggers above handler
这存在吗?我正在使用 jQuery,不想仅仅为了这种能力而导入整个插件或另一个库,所以我只对一个简短的解决方案感兴趣。
最佳答案
您可以使用 Mutation Events但这些事件已在 DOM 事件规范中标记为已弃用,因为 API 的设计存在缺陷。
The MutationEvent interface was introduced in DOM Level 2 Events, but has not yet been completely and interoperably implemented across user agents. In addition, there have been critiques that the interface, as designed, introduces a performance and implementation challenge. DOM4 provides a new mechanism using a MutationObserver interface which addresses the use cases that mutation events solve, but in a more performant manner. Thus, this specification describes mutation events for reference and completeness of legacy behavior, but deprecates the use of the MutationEvent interface.
一个简单的选择是使用 .trigger()
方法:
var $div = $(div).on('appendedToDOM', function() {
console.log('appended');
});
// ...
$div.appendTo('body').trigger('appendedToDOM');
您还可以创建附加元素并触发自定义事件的辅助函数:
function append(elem, target, cEvent) {
if (typeof target === 'undefined') var target = document.body;
if (typeof cEvent === 'undefined') var cEvent = 'appendedToDOM';
$(elem).appendTo(target).trigger(cEvent);
}
// Usage
append(element [, targetElement] [, customEvent]);
关于javascript - 为尚未附加的元素绑定(bind) "insertion into DOM event",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18697642/