<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
不起作用。我一直在寻找在线语法,我找不到任何东西。
答案 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
迭代数组:
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;