Previously one could hook into jQuery's domManip
method to catch all jQuery dom manipulations and see what elements where inserted etc. but the jQuery team shut that down in jQuery 3.0+ as it's generally not a good solution to hook into jQuery methods that way, and they've made it so the internal domManip
method no longer is available outside the core jQuery code.
Mutation Events have also been deprecated, as before one could do something like
$(document).on('DOMNodeInserted', function(e) {
if ( $(e.target).hasClass('MyClass') ) {
//element with .MyClass was inserted.
}
});
this should be avoided, and today Mutation Observers should be used instead, which would work like this
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation)
if (mutation.addedNodes && mutation.addedNodes.length > 0) {
// element added to DOM
var hasClass = [].some.call(mutation.addedNodes, function(el) {
return el.classList.contains('MyClass')
});
if (hasClass) {
// element has class `MyClass`
console.log('element ".MyClass" added');
}
}
});
});
var config = {
attributes: true,
childList: true,
characterData: true
};
observer.observe(document.body, config);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…