JavaScript。侦听特定标签上的DOM变化,而无需轮询。

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

我想创建一个监听器,当DOM更新被应用到一个新的标签时,它可以检测指定标签上的变化。<audio> 标签,并只对这些新标签应用一个类。

如何只为一个标签创建一个指定的监听器?

出于性能方面的考虑,我不希望为一个标签创建一个 setInterval. 有没有其他方法可以实现这个目标,如何实现?

javascript html dom addeventlistener
1个回答
2
投票

如果我没理解错的话,你想检测当一个人的 <audio/> 元素被添加到你的文档中,并在检测到这个事件时,为这个新添加的元素分配一个CSS类 audio 元素。

一种避免投票的可能性是使用一个叫做 突变观察者 - 一个简单的解决方案是观察 body 元素的任何变化。childListsubtree 并且,对于检测到的任何由新添加的 audio 节点,将所需的类添加到该 audio 节点。

/* Mutation handler will assign "addedAudio" class to
any newly added audio elements */
function onMutation(mutations) {

  for (const mutation of mutations) {
    if (mutation.type === 'childList') {

      /* This mutation type is a change to tree nodes in dom */
      for (const addedNode of mutation.addedNodes) {
        if (addedNode.nodeName === 'AUDIO') {

          /* The node triggering this mutation is an audio node */
          addedNode.classList.add("addedAudio");
        }
      }
    }
  }
}

/* Create dom mutation observer with callback, and
bind observer to body (eg "root") of your web app
and watch all children and subtrees for any changes */
(new MutationObserver(onMutation))
.observe(document.querySelector("body"), {
  childList: true,
  subtree: true
})

/* For demo purpose only to simulate adding new audio element to document */
document.querySelector('button').addEventListener('click', () => {

  const audio = document.createElement("audio");
  audio.setAttribute('controls', true);
  audio.setAttribute('src', 'https://www.w3schools.com/html/horse.ogg');

  document.body.prepend(audio);
});
.addedAudio {
  border: 1px solid red;
}
<button>Add audio</button>

请注意,更有效的方法是观察一个DOM节点,它的子节点较少,子树较浅,等等。例如,如果所有的 audio 元素被添加到一个普通的DOM元素中,考虑观察该元素,而不是观察 body.

希望对用户有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.