JavaScript 是否可以监听属性值的变化?例如:
var element=document.querySelector('…');
element.addEventListener( ? ,doit,false);
element.setAttribute('something','whatever');
function doit() {
}
我想对 something
属性中的任何更改做出响应。
我已经阅读了 MutationObserver
对象,以及该对象的替代方案(包括使用动画事件的对象)。据我所知,它们是关于实际 DOM 的更改。我对特定 DOM 元素的属性更改更感兴趣,所以我不认为仅此而已。当然,在我的实验中,它似乎不起作用。
我想在没有 jQuery 的情况下完成此操作。
谢谢
最佳答案
您需要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");
// Example of accessing the element for which
// event was triggered
mutation.target.textContent = "Attribute of the element changed";
}
console.log(mutation.target);
});
});
observer.observe(element, {
attributes: true //configure it to listen to attribute changes
});
<div id="test">Dummy Text</div>
此外,mutation.target属性给出了对突变/更改节点的引用。
关于JavaScript:监听属性变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41424989/