JavaScript:监听属性变化? [英] JavaScript: Listen for attribute change?
问题描述
是否可以在 JavaScript 中监听属性值的变化?例如:
Is it possible in JavaScript to listen for a change of attribute value? For example:
var element=document.querySelector('…');
element.addEventListener( ? ,doit,false);
element.setAttribute('something','whatever');
function doit() {
}
我想对 something
属性中的任何更改做出响应.
I would like to respond to any change in the something
attribute.
我已经阅读了 MutationObserver
对象,以及它的替代品(包括使用动画事件的那个).据我所知,它们是关于对实际 DOM 的更改.我对特定 DOM 元素的属性更改更感兴趣,所以我认为不是这样.当然在我的实验中它似乎不起作用.
I have read up on the MutationObserver
object, as well as alternatives to that (including the one which uses animation events). As far as I can tell, they are about changes to the actual DOM. I’m more interested in attribute changes to a particular DOM element, so I don’t think that’s it. Certainly in my experimenting it doesn’t seem to work.
我想在没有 jQuery 的情况下 做到这一点.
I would like to do this without jQuery.
谢谢
推荐答案
您需要 MutationObserver,在代码片段中我使用了 setTimeout
来模拟修改属性
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>
这篇关于JavaScript:监听属性变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!