[英]observing Attribute change in a div
我正在嘗試觀察到的變化
<div id="one" class="elem" data-result="inr"></div>
此div中的data-result屬性。
大多數舊方法似乎已被貶值。 我意識到MutationObserver是最好的進行方法。 並獨自寫了一篇沒用的書。 我發現了類似的onattrchange.js 。
為此,我試圖解決我面臨的問題。
我創建了這個jsfiddle ,它能夠檢測輸入更改(使用$(document).on),但不能檢測到data-result屬性的更改。
我嘗試了兩種方法...(1) ('body').attrchange
(2) $(document).on('attrchange',...)
我不確定為什么這行不通。 (我對js和jquery也很陌生,可以通過編碼學習)
編輯:我發現了一個類似的小提琴 ,正是我想要的。 我正在做類似的事情,但我想我犯了一些小錯誤。
我發現了代碼問題。
onattrchange.js似乎無法識別使用進行的更改
$("element").data("result",$(this).val());
它檢測
$("element").attr("data-result",$(this).val());
我加了工作的小提琴 。
我一直在尋找相同的解決方案,但不想使用任何第三方庫。 在Google和本網站上進行了一些挖掘之后,我在https://stackoverflow.com/a/58501827/6879925上找到了解決方案
// code to change image src in each 1000ms. count = 0; setInterval(function () { var sourceElement = document.querySelector('#div1'); sourceElement.setAttribute('data-src', 'something' + count); sourceElement.innerHTML = 'something' + count; count++; }, 2000); function startMutationObserver(tNode, c) { // Select the node that will be observed for mutations const targetNode = tNode ? tNode : document; // Options for the observer (which mutations to observe) const config = c ? c : { attributes: true, childList: true, subtree: true }; // Callback function to execute when mutations are observed const callback = function (mutationsList, observer) { for (let mutation of mutationsList) { if (mutation.type === 'childList') { targetNode.dispatchEvent(new CustomEvent('newChild', { detail: mutation })); } else if (mutation.type === 'attributes') { targetNode.dispatchEvent(new CustomEvent('attributeChange', { detail: mutation })); } } } // 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(); } // call this function to start observing DOM element change startMutationObserver(document); // code to listen custom event and filter custom event as per requirement document.addEventListener('attributeChange', function (e) { // console.log(e); const ele = e.detail; if (ele.target.matches('div[data-src]') && ele.attributeName == 'data-src') { var src = e.detail.target.getAttribute('data-src'); console.log('new src=', src); } });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id='div1' data-src="something">Something....</div> </body> </html>
我認為這是我有史以來最好的HTML / javaScript屬性更改檢測解決方案之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.