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

每次 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...

我希望我的问题足够清楚😇😊


缥缈止盈
浏览 204回答 1
1回答

慕慕森

您可以使用Mutation Observers实现此目的// Select the node that will be observed for mutationsconst targetNode = document.getElementById('myDiv');// Options for the observer (which mutations to observe)const config = { attributes: true };// Callback function to execute when mutations are observedconst callback = function(mutationsList, observer) {&nbsp; &nbsp; // Use traditional 'for loops' for IE 11&nbsp; &nbsp; for(let mutation of mutationsList) {&nbsp; &nbsp; &nbsp; &nbsp; if (mutation.type === 'attributes') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(myDivAttr == "type-1"){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; typeOneFunction();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;else if(myDivAttr == "type-2"){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;typeTwoFunction();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }};// Create an observer instance linked to the callback functionconst observer = new MutationObserver(callback);// Start observing the target node for configured mutationsobserver.observe(targetNode, config);// Later, you can stop observingobserver.disconnect();https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver我没有测试该代码*
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript