JavaScript:听取属性更改?

Man*_*ngo 26 javascript attributes event-handling custom-events

在JavaScript中是否可以侦听属性值的更改?例如:

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

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

function doit() {

}
Run Code Online (Sandbox Code Playgroud)

我想回应something属性的任何变化.

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

我想在没有 jQuery的情况下这样做.

谢谢

Sat*_*pal 50

你需要MutationObserver,我在片段中用来setTimeout模拟修改属性

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
});
Run Code Online (Sandbox Code Playgroud)
<div id="test">Dummy Text</div>
Run Code Online (Sandbox Code Playgroud)


sci*_*per 12

这个问题已经有了答案,但我想分享一下我的经验,因为突变观察者没有给我带来所需的见解。

注意这是某种 hacky 解决方案,但(至少)出于调试目的相当不错。

您可以覆盖setAttribute特定元素的功能。通过这种方式,您还可以打印调用堆栈,并了解“谁”更改了属性值:

// 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); 
};
Run Code Online (Sandbox Code Playgroud)