HTML DOM中的HTMLCollection是活动的;当底层文档发生更改时,它会自动更新。
我试图写一个简单的脚本,为一个网站,经常添加元素,重新着色这些元素的基础上。
现在,出于性能方面的原因,我不想让循环不断地运行并检查新元素。
如何使用活动的HTMLcollectio nand并对其中的每个元素执行函数,即使是添加的新元素?
如果我能做到这一点,它应该导致一个永远不会结束的脚本,并重新着色所有新元素。
感谢任何人的帮助!
发布于 2018-09-23 05:19:52
我会使用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>
https://stackoverflow.com/questions/52460788
复制相似问题