JavaScript: Listen for attribute change?

你说的曾经没有我的故事 提交于 2019-11-26 19:58:34

问题


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() {

}

I would like to respond to any change in the something attribute.

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.

I would like to do this without jQuery.

Thanks


回答1:


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>


来源:https://stackoverflow.com/questions/41424989/javascript-listen-for-attribute-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!