【问题标题】:JavaScript how do i iterate over every current and future element in a HTMLcollection?JavaScript 如何遍历 HTML 集合中的每个当前和未来元素?
【发布时间】:2018-09-22 20:54:15
【问题描述】:

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

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

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

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

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

任何帮助表示赞赏!

【问题讨论】:

  • 这不是它的工作原理。你将集合保存在一个全局变量中,每当你循环它时,它将包含当前的 DOM 元素。但是,只要集合发生变化,就不会自动执行循环。
  • 这是XY problem 的一个主要示例 - 您要解决的真正问题是“更改任何符合条件的元素,即使它们是稍后添加的”,但您正在询问如何遍历 HTMLCollection。如果你能专注于问题的核心,你就能找到更好的替代方案。在我的脑海中,似乎MutationObserver 更适合。
  • @vlaz 哦,这是有道理的。并且你已经看到了建议突变观察服务器的答案,我希望我能弄清楚如何使这项工作。谢谢。

标签: javascript loops htmlcollection


【解决方案1】:

我会使用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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    • 2018-03-14
    • 2011-01-09
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多