gpt4 book ai didi

javascript - 当元素丢失属性时触发函数

转载 作者:行者123 更新时间:2023-11-29 10:10:26 26 4
gpt4 key购买 nike

有没有办法在元素丢失某些自定义 属性时触发函数?例如,当 custom_attribute 被删除时,然后显示一些警报。有什么办法呢?纯 JS 更可取,尽管 jQuery 也可以。

<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()。因此,您可以检查特定属性是否丢失或更改。

关于javascript - 当元素丢失属性时触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34546167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com