在JavaScript中是否可以监听属性值的更改?例如:
var element=document.querySelector('…');
element.addEventListener( ? ,doit,false);
element.setAttribute('something','whatever');
function doit() {
}
我想响应something
属性中的任何更改。
我已经阅读了mutationobserver
对象,以及该对象的替代对象(包括使用动画事件的对象)。据我所知,它们是关于实际DOM的更改。我更感兴趣的是对一个特定DOM元素的属性更改,所以我不认为仅此而已。当然,在我的实验中,这似乎不起作用。
我希望在没有jQuery的情况下这样做。
谢谢
您需要MutationObserver,在这里的片段中,我使用了settimeout
来模拟修改属性
null
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>