观察尚不存在的目标节点上的突变

问题描述 投票:0回答:1

是否可以在尚不存在的 DOM 节点上观察突变?

示例:

我的应用程序在某个时刻创建了一个 div:

<div id="message" data-message-content="foo" data-message-type="bar" />

我想关注这个div的创建和变化。

var mutationObserver = new MutationObserver(function(mutations){
  // Some code to handle the mutation.
});

mutationObserver.observe(
    document.querySelector('#message'),
        { 
            attributes: true, 
            subtree: true, 
            childList: true, 
            characterData: false 
        }
    );
);

现在这会返回一个 error,因为

#message
为 null(div 尚未创建)。

Failed to execute 'observe' on 'MutationObserver': parameter 1 is not of type 'Node'.

一个明显的解决方案是观察

body
并检查是否有任何突变是由
div#Message
创建的,但这似乎是一个坏主意/或者可能对性能不利。

javascript mutation-observers
1个回答
105
投票

只能观察到已有的节点。

您可以在 MutationObserver 回调中使用

document.getElementById()
,与枚举所有变异节点相比,它的速度非常快(另请参阅MutationObserver 的性能)。

function waitForAddedNode(params, callback) {
    new MutationObserver(mutations => {
        var el = document.getElementById(params.id);
        if (el) {
            this.disconnect();
            callback(el);
        }
    }).observe(params.parent || document, {
        subtree: !!params.recursive || !params.parent,
        childList: true,
    });
}

用途:

waitForAddedNode({
    id: 'message',
    //parent: document.querySelector('.container'),
    recursive: true,
}, el => {
    console.log(el);
});
© www.soinside.com 2019 - 2024. All rights reserved.