簡體   English   中英

JavaScript我如何遍歷HTMLcollection中的每個當前和將來的元素?

[英]JavaScript how do i iterate over every current and future element in a HTMLcollection?

HTML DOM中的HTMLCollection是實時的; 當基礎文檔更改時,它會自動更新。

我試圖為一個經常添加元素的網站編寫一個簡單的腳本,該腳本根據條件為這些元素重新着色。

現在,出於性能原因,我不想讓循環持續運行並檢查新元素。

我將如何使用實時HTML集合並在其中的每個元素上執行一個函數,甚至添加了新元素?

如果我能做到這一點,它將導致腳本永遠無法完成,並為所有新元素重新着色。

任何幫助表示贊賞!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM