我在幾年前看到過類似的問題,但它們對我沒有用處。我在這裏重複了一些類似的問題,因爲可能會有新的更新。如何在添加,刪除屬性或使用純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) –