【发布时间】:2016-08-26 05:25:26
【问题描述】:
对于给定数量的html节点,比如
<div id="main">
<div class="pre1">
<div class="prop1"></div>
<div class="prop2"></div>
<div class="prop3"></div>
</div>
<div class="pre2">
<div class="prop1"></div>
<div class="prop2"></div>
<div class="prop3"></div>
</div>
<div class="pre3">
<div class="prop1"></div>
<div class="prop2"></div>
<div class="prop3"></div>
</div>
</div>
向 prop2 节点添加文本的方式类似于
var el = document.getElementById('main').firstElementChild;
while (el) {
var el2 = el.firstElementChild;
while (el2) {
if (el2.className == 'prop2')
el2.textContent = 'hola';
el2 = el2.nextElementSibling;
}
el = el.nextElementSibling;
}
https://jsfiddle.net/g9zoa1vz/
问题在于,从概念上讲,当您第一次定位“prop2”项目时,如果您知道您的数据结构是不变的,那么您就是在浪费时间再次搜索该位置。
问题是:有没有办法存储 DOM 位置,以便在您第一次搜索后,您可以执行类似的操作
var el = document.getElementById('main').firstElementChild;
while (el) {
el.firstElementChild.nextElementSibling.textContent = 'hola';
el = el.nextElementSibling;
}
然后在要分析许多节点时节省大量循环时间?
【问题讨论】:
-
document.querySelectorAll(".prop2").forEach(function() {})你的问题是 X/Y 问题... -
您可以将必要的元素放入数组中,然后对其进行迭代。
-
您知道您可以使用
document.querySelectorAll('.prop2')一次获取所有prop2节点,对吧?您甚至可以更具体:document.querySelectorAll('.pre1 > .prop2')将仅获取那些是pre1的直接子节点的节点... -
老实说,如果这段代码没有成为应用程序性能的瓶颈,我不会为优化它而烦恼。我们是在谈论 10 万个节点吗?它在哪里大大降低了应用程序的速度?
-
@SamuelToh 这更像是一个理论问题,但我已经将解决方案应用于我的代码中的一个函数,现在它不是等待 1 秒,而是立即发生(这实际上是一个重要的交易)
标签: javascript loops dom recursive-datastructures