JavaScript: 侦听属性更改?

在 JavaScript 中是否可以监听属性值的变化? 例如:

var element=document.querySelector('…');
element.addEventListener( ? ,doit,false);


element.setAttribute('something','whatever');


function doit() {


}

我希望对 something属性中的任何更改作出响应。

我已经阅读了 MutationObserver对象,以及其他替代品(包括使用动画事件的对象)。据我所知,它们是关于对实际 DOM 的更改。我更感兴趣的是对特定 DOM 元素的属性更改,所以我不认为这就是问题所在。当然,在我的实验中,它似乎不起作用。

我想做这个 没有 jQuery。

谢谢

83027 次浏览

You need MutationObserver, Here in snippet I have used setTimeout to simulate modifying attribute

var element = document.querySelector('#test');
setTimeout(function() {
element.setAttribute('data-text', 'whatever');
}, 5000)


var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === "attributes") {
console.log("attributes changed")
}
});
});


observer.observe(element, {
attributes: true //configure it to listen to attribute changes
});
<div id="test">Dummy Text</div>

This question is already answered, but I'd like to share my experiences, because the mutation observer did not bring me the insights in needed.

Note This is some kind of hacky solution, but for (at least) debugging purposes quite good.

You can override the setAttribute function of a particalar element. This way you can also print the callstack, and get an insight of "who" changed the attribute value:

// select the target element
const target = document.querySelector("#element");
// store the original setAttribute reference
const setAttribute = target.setAttribute;
// override setAttribte
target.setAttribute = (key: string, value: string) => {
console.trace("--trace");
// use call, to set the context and prevent illegal invocation errors
setAttribute.call(target, key, value);
};