用于循环条件评估

时间:2018-05-03 14:43:48

标签: javascript algorithm

我有这个HTML代码

<div id="first">
  <div id="second">
  </div>
</div>

我想将一个孩子附加到每个现有的div。

当我使用此代码时

function appendC() {
  var divsVar = document.getElementsByTagName("div");

  for (var i = 0; i < divsVar.length; i++) {
    var new_div = document.createElement("div");
    div[i].appendChild(new_div);
  }
}

它进入无限循环的功能。但我无法理解为什么。

当调用该函数时,它在我的示例中为var divsVar分配了一个包含2个div的数组。除非我再次调用该功能,否则永远不要再执行。但是divsVar.length在每个循环中都会改变。这怎么可能?? divsVar.length应保持不变??

如果我使用像那样的临时变量

 function appendC() {
      var divsVar = document.getElementsByTagName("div");
    var _temp = divsVar.length;
      for (var i = 0; i < _temp; i++) {
        var new_div = document.createElement("div");
        div[i].appendChild(new_div);
      }
    }

它就像一个魅力。

3 个答案:

答案 0 :(得分:4)

.getElementsByTagName()方法返回实时HTMLCollection

您可以将集合转换为数组(例如[].slice.call(collection)),也可以使用其他方法,例如.querySelectorAll()返回静态NodeList

https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

答案 1 :(得分:2)

getElementsByTagName()返回包含实时HTMLCollection的对象。每次更新dom时都会更新。在for循环中,在每次迭代之后,在当前dom上再次评估length属性。
因为你要向dom添加div,所以这个循环将永远运行。

这与_temp变量一起使用的原因是因为您只评估HTMLCollection一次的长度。

我认为最好的解决方案是预先评估长度,就像你上一个例子一样。

答案 2 :(得分:1)

getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name.

这意味着即使您没有再次调用它,它仍在更新中。要解决这个问题,只需使用

即可

document.querySelectorAll("div")

返回A non-live NodeList containing one Element object for each element that matches at least one of the specified selectors.

相关问题