gpt4 book ai didi

javascript - 使用 js 实时检测 DOM 自定义数据属性值的变化并在变化发生时运行函数

转载 作者:行者123 更新时间:2023-11-28 03:21:54 24 4
gpt4 key购买 nike

每当 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/

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