首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >JavaScript如何遍历HTMLcollection中当前和未来的每个元素?

JavaScript如何遍历HTMLcollection中当前和未来的每个元素?
EN

Stack Overflow用户
提问于 2018-09-23 04:54:16
回答 1查看 243关注 0票数 0

HTML DOM中的HTMLCollection是活动的;当底层文档发生更改时,它会自动更新。

我试图写一个简单的脚本,为一个网站,经常添加元素,重新着色这些元素的基础上。

现在,出于性能方面的原因,我不想让循环不断地运行并检查新元素。

如何使用活动的HTMLcollectio nand并对其中的每个元素执行函数,即使是添加的新元素?

如果我能做到这一点,它应该导致一个永远不会结束的脚本,并重新着色所有新元素。

感谢任何人的帮助!

EN

回答 1

Stack Overflow用户

发布于 2018-09-23 05:19:52

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

代码语言:javascript
复制
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)
代码语言:javascript
复制
<div id="watch">
  <div>One</div>
  <div>Two</div>
  <div>Three</div>
</div>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52460788

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档