指向JavaScript数组中多个元素的正确语法是什么?

时间:2016-12-01 20:54:55

标签: javascript arrays

<body>

<p class="initial">Number One!</p>
<p class="initial">Number Two!</p>
<p class="initial">Number Three!</p>

<script>
var x = document.getElementsByClassName("initial");
x[0].innerHTML = "<span class=\"fix\">super duper</span>";
</script>

</body>

x[0].innerHTML指向第一个元素。但是,如果我想更改数组中几个元素的innerHTML怎么办?例如第一个和第三个。 x[0, 2].innerHTML不起作用。我一直在寻找在线语法,我找不到任何东西。

3 个答案:

答案 0 :(得分:3)

考虑for loop多次运行代码:

for (var i = 0; i < 3; i++) {
    x[i].innerHTML = "<span class=\"fix\">super duper</span>";
}

如果您需要特定元素,请创建一个数组并使用forEach loop进行迭代:

var desiredElems = [1, 3, 7, 9];
desiredElems.forEach(function(element) {
    x[element].innerHTML = "<span class=\"fix\">super duper</span>";
});

答案 1 :(得分:3)

分配是表达式,返回指定值,因此您可以执行以下操作:

var x = document.getElementsByClassName("initial");
x[0].innerHTML = x[2].innerHTML = "<span class=\"fix\">super duper</span>";
<p class="initial">Number One!</p>
<p class="initial">Number Two!</p>
<p class="initial">Number Three!</p>

如果您想更改多个索引,可以将索引定义为数组并使用循环:

var indices = [0, 2];

var x = document.getElementsByClassName("initial");
indices.forEach(function(i) {
  x[i].innerHTML = "<span class=\"fix\">super duper</span>";
})
<p class="initial">Number One!</p>
<p class="initial">Number Two!</p>
<p class="initial">Number Three!</p>

答案 2 :(得分:2)

您可以使用for...of迭代数组:

&#13;
&#13;
var x = document.getElementsByClassName("initial");
for (var i of [0,2])
  x[i].innerHTML = "<span class=\"fix\">super duper</span>";
&#13;
<p class="initial">Number One!</p>
<p class="initial">Number Two!</p>
<p class="initial">Number Three!</p>
&#13;
&#13;
&#13;