我有一些元素具有相同的类名,我将它们的innerHTML插入另一个具有类名“ show”的元素中。预期输出为12345,但仅显示最后一个元素的innerHTML(5)。这是我的代码段;
source = document.getElementsByClassName("source");
show = document.getElementsByClassName("show");
for(var i = 0; i < source.length; i++)
show[0].innerHTML = source[i].innerHTML;
.show{
display:block;
}
<span class="source">1</span>
<span class="source">2</span>
<span class="source">3</span>
<span class="source">4</span>
<span class="source">5</span>
<span class="show"></span>
答案 0 :(得分:1)
添加+
以添加数字show[0].innerHTML += source[i].innerHTML;
source = document.getElementsByClassName("source");
show = document.getElementsByClassName("show");
debugger;
for(var i = 0; i < source.length; i++){
show[0].innerHTML += source[i].innerHTML;
}
.show{
display:block;
}
<span class="source">1</span>
<span class="source">2</span>
<span class="source">3</span>
<span class="source">4</span>
<span class="source">5</span>
<span class="show"></span>
答案 1 :(得分:1)
您可以使用.reduce()
将HTML连接到每个元素的累加器。 Array.from
仅允许您在DOM元素数组上使用.reduce()
:
var source = Array.from(document.getElementsByClassName("source"))
var show = document.getElementsByClassName("show")[0];
show.innerHTML = source.reduce((a, el) => a += el.innerHTML, '')
.show {
display: block;
}
<span class="source">1</span>
<span class="source">2</span>
<span class="source">3</span>
<span class="source">4</span>
<span class="source">5</span>
<span class="show"></span>
答案 2 :(得分:0)
使用show[0].innerHTML += source[i].innerHTML;
答案 3 :(得分:0)
source = document.getElementsByClassName("source");
show = document.getElementsByClassName("show");
for(var i = 0; i < source.length; i++)
show[0].innerHTML += source[i].innerHTML;
.show{
display:block;
}
<span class="source">1</span>
<span class="source">2</span>
<span class="source">3</span>
<span class="source">4</span>
<span class="source">5</span>
<span class="show"></span>