MutationObserver 在新节点上循环

MutationObserver looping on new nodes

我在这里要做的是通过使一些文本节点成为“跨度”元素来突出显示它们。当新 message/comment 加载时,我希望它也能在新添加的节点上工作。但是,我发现 MutationObserver 一直在寻找新添加的节点。可能是因为 doSomething 创建了新节点,它会被 MutationObserver 重新发现。我如何防止这种情况发生?不确定我是否应该将 MutationObserver 放在 EventListener 中,但它似乎无法在它之外工作。

document.addEventListener('DOMContentLoaded', function() {
    var allTextNodes = textNodesUnder(document.body);
    doSomething(allTextNodes);

    // Select the node that will be observed for mutations
    const targetNode = document.body;

    // Options for the observer (which mutations to observe)
    const config = { attributes: true, childList: true, subtree: true };

    // Callback function to execute when mutations are observed
    const callback = function(mutationsList, observer) {
        function scanning(el) {
            // el.style.visibility = "hidden";
            var newTextNodes = textNodesUnder(el);
            doSomething(newTextNodes);
        }
    };

    // 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); 
    //observer.disconnect(); //will not work if disconnect here
});

function doSomething(node) {
    var newItem = document.createElement("SPAN");
    newItem.style.backgroundColor = "red";
    var textnode = document.createTextNode(node.textContent);
    newItem.appendChild(textnode);
    node.replaceWith(newItem); 
}

您的 MutationObserver 回调会被调用 每次您更改节点的内容时 包括您在回调本身内这样做的次数. 在回调中进行更改之前,调用 observer.disconnect(),然后在进行更改后使用 observe 重新连接:

const callback = function(mutationsList, observer) {
    function scanning(el) {
        observer.disconnect();
        // el.style.visibility = "hidden";
        var newTextNodes = textNodesUnder(el);
        doSomething(newTextNodes);
        observer.observe(targetNode, config);
    }
};