首页 > 解决方案 > 侦听 HTML 元素,无需 setInterval

问题描述

我想知道是否可以在不使用 setInterval 的情况下侦听 DOM 中的元素,就像我现在正在做的那样:

var interval = setInterval(() => {
  var div = document.querySelector('.test');
  if (div != null) {
    clearInterval(interval);
    console.log(div);
  }
}, 1000);

我的问题是这个特定的 div 在 10-12 分钟后随机加载到 DOM 中。我认为 setInterval 我只是一个丑陋的解决方案。所以我的问题是,是否可以在不使用间隔的情况下监听 DOM 中的新 div?

标签: javascriptjquery

解决方案


对于Mutation Observer来说,这似乎是一项不错的工作。它会观察你的 DOM 上的一个静态父节点,并提醒你结构的任何变化。test您可以侦听带有要添加的类的子节点。例如:

// this setTimeout is only to show this example working. it is not needed 
setTimeout(() => {
  let aDiv = document.createElement('div');
  aDiv.className = 'test';
  document.getElementById('parent').appendChild(aDiv);
}, 3000);

let targetNode = document.getElementById('parent');

let config = {
  attributes: false,
  childList: true,
  subtree: true
};

// Callback function to execute when mutations are observed
let callback = function(mutationsList, observer) {
  for (let mutation of mutationsList) {
    if (mutation.type == 'childList') {
      for (let node of mutation.addedNodes) {
        if (node.className === "test") {
          console.log("a node with class test was added!");
          // stop observing
          observer.disconnect();
        }
      }
    }
  }
};

// Create an observer instance linked to the callback function
let observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);
<div id="parent">

</div>


推荐阅读