【问题标题】:Javascript DOM add/remove events [duplicate]Javascript DOM添加/删除事件[重复]
【发布时间】:2018-10-21 07:24:38
【问题描述】:

我希望在从 DOM 树中删除一个元素时做一些清理工作,更具体地说,ParentElement.removeChild(ChildElement)。我想知道当ChildElement 被删除时,是否有任何事件可以在我的代码中监听?

【问题讨论】:

    标签: javascript dom-events


    【解决方案1】:

    是的,您可以使用 MutationObserver 监听对 DOM 的操作。

    来自 MDN 文档的示例:

    // Select the node that will be observed for mutations
    var targetNode = document.getElementById('some-id');
    
    // Options for the observer (which mutations to observe)
    var config = { attributes: true, childList: true };
    
    // Callback function to execute when mutations are observed
    var callback = function(mutationsList) {
        for(var mutation of mutationsList) {
            if (mutation.type == 'childList') {
                console.log('A child node has been added or removed.');
            }
            else if (mutation.type == 'attributes') {
                console.log('The ' + mutation.attributeName + ' attribute was modified.');
            }
        }
    };
    
    // Create an observer instance linked to the callback function
    var observer = new MutationObserver(callback);
    
    // Start observing the target node for configured mutations
    observer.observe(targetNode, config);
    
    // Later, you can stop observing
    observer.disconnect();
    

    【讨论】:

      【解决方案2】:

      以前您可以使用像 DOMNodeRemoved 这样的突变事件,这些事件已被 MutationObserver 弃用:

      var observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
          const removedNodes = mutation.removedNodes;
          // Cast NodeList to Array to have access to .includes method
          if (Array.from(removedNodes).includes(childElement)) {
            console.log('childElement removed');
          }
        })
      });
      
      observer.observe(document.getElementById('parentElement'), {
        childList: true
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多