我想在彼此之间将数组显示为html。
示例:
let cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
我得到的是:萨博,沃尔沃,宝马
我想要的是:
萨博
沃尔沃
宝马
有人可以帮我吗?
答案 0 :(得分:1)
join
带有br
元素的数组。这里我用过insertAdjacentHTML
...
let cars = ["Saab", "Volvo", "BMW"];
document.body.insertAdjacentHTML('beforeend', cars.join('<br/>'));
...但是innerHTML
也可以。
let cars = ["Saab", "Volvo", "BMW"];
document.body.innerHTML = cars.join('<br/>');
答案 1 :(得分:0)
这是一个快速的解决方案:)
470
471
答案 2 :(得分:0)
const cars = ["Saab", "Volvo", "BMW"];
const list = document.getElementById("demo");
cars.forEach(car => {
let item = document.createElement("li");
item.innerText = car;
list.appendChild(item);
})
<ul id="demo"></ul>
答案 3 :(得分:0)
使用forEach遍历cars数组,并在演示元素现有内容的每个附加项上使用br标签
let cars = ["Saab", "Volvo", "BMW"];
cars.forEach(v => {
document.getElementById("demo").innerHTML += v + '<br />';
})
codepen-https://codepen.io/nagasai/pen/MZabXm
let cars = ["Saab", "Volvo", "BMW"];
cars.forEach(v => {
document.getElementById("demo").innerHTML += v + '<br />';
})
<div id="demo"></div>
答案 4 :(得分:0)
var cars = ["Saab", "Volvo", "BMW"];
var content = '';
for(var i=0; i<cars.length; i++){
content+= "<div>"+cars[i]+"</div>";
}
document.getElementById("demo").innerHTML = content;