我在几年前看到过类似的问题,但它们对我没有用处。我在这里重复了一些类似的问题,因为可能会有新的更新。如何在添加,删除属性或使用纯javascript更改其属性时获取事件
我想添加一个属性时,调用一个函数,删除文档中所有元素的元素(或其值改变)。它需要在所有浏览器中至少使用chrome和Mozilla Firefox。我想纯粹用javascript来实现它。
我试过以下代码
使用事件监听器。这适用于Mozilla Firefox,但不适用于Chrome。
document.addEventListener("DOMAttrModified", function(event){
console.log('DOMAttrModified invoked');
console.log(event);
});
使用观察者。它不起作用,它使错误(WebKitMutationObserver is not defined
)错误的Firefox。在chrome中,它不会发生任何错误,但它不会监听事件。
var element = document.body, bubbles = false;
var observer = new WebKitMutationObserver(function (mutations) {
mutations.forEach(attrModified);
});
observer.observe(element, { attributes: true, subtree: bubbles });
最后,我试了下面。
Element.prototype.setAttribute = function(name, value) {
console.log('attribute modified');
console.log(this);
console.log(name);
console.log(value);
};
很明显,它的工作在所有浏览器,但只能用setAttribute
设置属性值时。例如:var div = document.createElement('div');
但不包含div.style = 'color:green';
。当设置值如div.style = 'color:green';
/div.name = 'somename';
时,我也想获得事件。有什么办法可以做到这一点?
部分不幸的是,它现在不受浏览器支持。我用chrome和firefox试了一下,得到'Object.observe不是函数(匿名函数)'。 [说它从firefox文档中的浏览器中删除](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/observe) –