不推荐使用DomNodeInserted
。我能找到的MutationObserver
的唯一例子是显示要更新的元素,而不是添加。
监听动态创建的某个类的新元素的最佳方法是什么?
答案 0 :(得分:0)
您可以将正确的MutationObserverInit
传递给MutationObserver
来执行此操作。您必须将subtree
设置为true
,然后添加attributeFilter
:class
(与domNode的类名一样)
// select the target node
var target = document.getElementById('some-id');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation);
});
});
// configuration of the observer:
var config = { attributes: true, childList: false, characterData: false, subtree: true, attributeFilter: ['class']};
// pass in the target node, as well as the observer options
observer.observe(target, config);
var myElement = document.createElement('div');
myElement.innerHTML = 'foo';
target.appendChild(myElement);
//triggers the mutation observer
myElement.classList.add('bar');
JSFiddle:https://jsfiddle.net/7zwraaxz/3/
答案 1 :(得分:-1)
可能是你要求在添加课程后你想要触发一个事件:
$(document).on('click', function(){
$('#theid').addClass('classname').trigger('classChange');
});
$('#theid').on('classChange', function() {
// do stuff
});
如果有其他事情请解释: