观察div中的属性更改

时间:2013-10-16 13:15:28

标签: javascript jquery html css mutation-observers

我正在尝试观察对

的更改
<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也很新,通过编码学习)

编辑:我找到了一个类似的fiddle,它完全符合我的要求。我正在做类似的事情,但我想我犯了一些小错误。

2 个答案:

答案 0 :(得分:0)

我发现代码存在问题。

onattrchange.js似乎无法识别使用

所做的更改
$("element").data("result",$(this).val());

检测到

$("element").attr("data-result",$(this).val());

我添加了工作fiddle

答案 1 :(得分:0)

我一直在寻找相同的解决方案,但不想使用任何第三方库。 在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属性更改检测解决方案之一。