当元素失去属性时激发函数



当元素失去一些自定义属性时,有没有办法激发函数?例如,删除custom_attribute后,显示一些警告。怎么做?虽然jQuery也可以,但最好使用纯JS。

<div class="someclass" custom_attribute>...</div>

您可以使用MutationObserver:

// select the target node
var target = document.querySelector('.someclass');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    fire_function();
    console.log(mutation.type);
  });    
});
// configuration of the observer:
var config = { attributes: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
// later, you can stop observing
observer.disconnect();

每当属性发生更改时,就会触发fire_function()。因此,您可以检查特定属性是否丢失或更改。

最新更新