JavaScript:侦听属性更改? [英] JavaScript: Listen for attribute change?

查看:188
本文介绍了JavaScript:侦听属性更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在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.setAttriubte('something','whatever');

function doit() {

}

我想对某些属性中的任何更改做出回应。

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 MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;

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">
</div>

这篇关于JavaScript:侦听属性更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆