Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript,反复查找DOM元素_Javascript_Loops_Dom_Recursive Datastructures - Fatal编程技术网

javascript,反复查找DOM元素

javascript,反复查找DOM元素,javascript,loops,dom,recursive-datastructures,Javascript,Loops,Dom,Recursive Datastructures,对于给定数量的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"&g

对于给定数量的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”项时,如果知道数据结构是恒定的,那么再次搜索位置是在浪费时间

问题是:是否有一种存储DOM位置的方法,以便在第一次搜索之后,可以执行以下操作

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;
}
var el = document.getElementById('main').firstElementChild;
while (el) {
  el.firstElementChild.nextElementSibling.textContent = 'hola';
  el = el.nextElementSibling;
}

然后在分析多个节点时节省大量的循环时间?

您的问题可以通过使用

注意我们使用for循环进行迭代,尽管有些浏览器允许forEach

更多迭代方法:

window.onload=function(){
var prop2=document.queryselectoral(#main.prop2”);
对于(var i=0,n=prop2.length;i请尝试下面的代码

var ele=document.queryselectoral(“.prop2”);
var l=长度;

对于(i=0;i
document.queryselectoral(.prop2”).forEach(function(){})来说,您的问题是一个X/Y问题……您可以将必需的元素推入数组中,然后对其进行迭代。您知道可以使用
document.queryselectoral('.prop2'))
一次获取所有
prop2
节点,对吗?您甚至可以更具体一点:
document.queryselectoral('.pre1>.prop2'))
只会得到那些是
pre1
直接子节点的节点。老实说,如果这段代码不影响应用程序的性能,我就不会为优化它而操心。我们是在谈论10万个节点吗?这会大大降低应用程序的速度吗?@SamuelToh这更像是一个理论探索ion,但我已经将解决方案应用于代码中的一个函数,现在它不是等待1秒,而是立即发生(实际上这是一个重要的交易)因为每个函数都是数组函数,querySelectorAll返回一个节点列表。编辑:好的,修复得很好;)Chrome实际上允许this@mplungjan谢谢,我早就知道了,但它早就被忘记了,所以非常感谢。我可以假设节点列表将始终按照外观顺序进行排序?是的。它就像jQuery$(“#main.prop2)我已经更新了我的答案,只得到了一次长度。是的,对我来说也是一样。我在给出答案时迟到了。因为每次循环执行它计算长度时,它都不会优化代码。如果循环执行100000次,那么它的长度计算就完成100000次。如果我们在之前定义长度,那么它只计算一次。
var ele=document.querySelectorAll(“.prop2”);var l=ele.length;for(…)
更合理请参见我的上述评论。让我们来看看。