增加计数器不会改变其他变量的值

时间:2018-06-18 21:04:42

标签: javascript

为什么在计数器值改变时,其他变量中使用的[counter]变量值不会改变?这与参考有关吗?



var counter = 0;

var allFields = document.getElementsByClassName('test')[counter].getElementsByClassName("pizza");

console.log(allFields);

counter++;

console.log(allFields); // expected result is to have 2 pizza elements.

<div class="test">
	<div class="pizza"></div>
</div>
<div class="test">
	<div class="pizza"></div>
	<div class="pizza"></div>
</div>
<div class="test">
	<div class="pizza"></div>
	<div class="pizza"></div>
  <div class="pizza"></div>
</div>
<div class="test">
	<div class="pizza"></div>
	<div class="pizza"></div>
  <div class="pizza"></div>
  <div class="pizza"></div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

当您使用allFields将字段分配到counter = 0时 - 它们将不再更改 - 您必须再次重新分配此变量。

我建议您将其创建为函数:

var allFields = function(i) {
  return document.getElementsByClassName('test')[counter].getElementsByClassName("pizza");
}

var counter = 0;
console.log(allFields(counter));

counter++;
console.log(allFields(counter));

另一种更好的方法是制作循环,例如:

for (var i = 0, i < 2; i++) {
  var allFields = document.getElementsByClassName('test')[i].getElementsByClassName("pizza");

  console.log(allFields);
}

答案 1 :(得分:1)

一旦设置

var allFields = document.getElementsByClassName('test')[counter]

创建对象。然后,您只能通过更改counter来动态更改对象。如果您希望能够这样做,那么只需保存

var allFields = document.getElementsByClassName('test')

并在需要时使用[counter]