首页 > 解决方案 > JavaScript 如何遍历 HTMLcollection 中的每个当前和未来元素?

问题描述

HTML DOM 中的 HTMLCollection 是活动的;它会在基础文档更改时自动更新。

我正在尝试为经常添加元素的网站编写一个简单的脚本,该脚本根据标准重新着色这些元素。

现在,出于性能原因,我不想让循环持续运行并检查新元素。

我将如何使用实时 HTMLcollectio n并在其中的每个元素上执行一个函数,即使是添加的新元素?

如果我能做到这一点,它应该会产生一个永远不会完成的脚本,并重新着色所有新元素。

任何帮助表示赞赏!

标签: javascriptloopshtmlcollection

解决方案


我会使用MutationObserver来完成这项任务。它将监视节点的更改,如果需要,它也会监视子树的更改(我认为这里不需要)。添加节点后,我们可以将节点发送到函数以在其上应用某些功能。在下面的示例中,我们只是随机选择一种颜色并设置背景。

let targetNode = document.getElementById('watch')

// Apply feature on the node
function colorNode(node) {
  let r = Math.floor(Math.random() * 255)
  let g = Math.floor(Math.random() * 255)
  let b = Math.floor(Math.random() * 255)
  node.style.background = `rgb(${r},${g},${b})`
}

// Watch the node for changes (you can watch the subTree if needed)
let observerOptions = {
  childList: true
}

// Create the callback for when the mutation gets triggered
let observer = new MutationObserver(mutationList => {
  // Loop over the mutations
  mutationList.forEach(mutation => {
    // For added nodes apply the color function
    mutation.addedNodes.forEach(node => {
      colorNode(node)
    })
  })
})

// Start watching the target with the configuration
observer.observe(targetNode, observerOptions)

/////////////////
/// Testing
/////////////////
// Apply the inital color
Array.from(targetNode.children).forEach(child => colorNode(child))

// Create nodes on an interval for testing
setInterval(() => {
  let newNode = document.createElement('div')
  // Some random text
  newNode.textContent = (Math.random() * 1000).toString(32)
  targetNode.appendChild(newNode)
}, 2000)
<div id="watch">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>


推荐阅读