简体   繁体   English

实时检测DOM定制数据属性的值变化,并使用js进行更改时运行函数

[英]Detect change in value of a DOM custom data attribute in real-time and run a function as the change occurs using js

I am trying to run a simple function each time there is a change in the value of a custom data attribute of a DOM element. 每当DOM元素的自定义数据属性的值发生变化时,我都试图运行一个简单的函数。

Here is an example below 这是下面的例子

<div id="myDiv" data-type="type-1">
    <!-- Some Content -->
</div>

In the HTML code above, i have a div with a custom data attribute of data-type with a value which i change using javascript. 在上面的HTML代码中,我有一个div ,其data-type的自定义数据属性的值是我使用javascript更改的值。 I would like to fire up a another function when ever the value of the attribute is changed depending on the value it holds. 当属性的值根据其拥有的值而改变时,我想启动另一个函数。

For instance Using an if-statement(which doesn't work! 😒) 例如,使用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...

I hope my question is clear enough😇😊 我希望我的问题足够清楚😇😊

You can achieve this using Mutation Observers 您可以使用突变观察者来实现

// 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 https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver

I didn't test that code* 我没有测试该代码*

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM