每当 DOM 元素的自定义数据属性的值发生变化时,我都会尝试运行一个简单的函数。
下面是一个示例
<div id="myDiv" data-type="type-1">
<!-- Some Content -->
</div>
在上面的 HTML 代码中,我有一个 div
,其自定义数据属性为 data-type
,其值是我使用 javascript 更改的。当属性的值根据它所保存的值而改变时,我想启动另一个函数。
例如使用 if 语句(这不起作用!😒)
var myDiv = document.getElementById("myDiv");
var myDivAttr = myDiv.getAttribute("data-type");
if(myDivAttr == "type-1"){
typeOneFunction();
}
else if(myDivAttr == "type-2"){
typeTwoFunction();
}
// and so on...
我希望我的问题足够清楚😇😊
最佳答案
您可以使用突变观察器来实现这一点
// Select the node that will be observed for mutations
const targetNode = document.getElementById('myDiv');
// Options for the observer (which mutations to observe)
const config = { attributes: true };
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
// Use traditional 'for loops' for IE 11
for(let mutation of mutationsList) {
if (mutation.type === 'attributes') {
if(myDivAttr == "type-1"){
typeOneFunction();
}
else if(myDivAttr == "type-2"){
typeTwoFunction();
}
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
我没有测试该代码*
关于javascript - 使用 js 实时检测 DOM 自定义数据属性值的变化并在变化发生时运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59072050/