使用Javascript将<span>标签分别附加到每个Array值

时间:2018-12-03 20:07:47

标签: javascript

这是我的第一个JavaScript项目,在将<span>标记分别附加到数组的每个值时遇到一些困难。到目前为止,我尝试过的所有操作都会产生一个<span>标签。使用原生JavaScript的优雅解决方案是什么?预先感谢您的帮助。

let numbers = [1990, 1991, 1992];

let history = [];
let historyContainer = document.getElementById("output");
let para = document.createElement("p");
history.push(numbers.join(" "));
        
for (let k in history) {
	let text = document.createElement("span");
	let node = document.createTextNode(history[k]);
	text.appendChild(node)
	para.appendChild(text);
	historyContainer.appendChild(para);
}
	
<div id="output">
	</div>

Link to external jsfiddle

4 个答案:

答案 0 :(得分:2)

history.push(numbers.join(" "));是您的问题-到循环运行时,history是一个由于连接而具有单个值1990 1991 1992的数组。实际上,您甚至不需要history,只需遍历numbers

let numbers = [1990, 1991, 1992];
let historyContainer = document.getElementById("output");
let para = document.createElement("p");

for (let k in numbers) {
  let text = document.createElement("span");
  let node = document.createTextNode(numbers[k]);
  text.appendChild(node)
  para.appendChild(text);
  historyContainer.appendChild(para);
}
span+span {
  margin-left: 4px;
}
<div id="output"></div>

答案 1 :(得分:0)

如果您想要一些简单快速的解决方案,请尝试以下操作:

var numbers = [1990, 1991, 1992],
  output = document.getElementById("output");

output.innerHTML = '<span>' + numbers.join('</span> <span>') + '</span>';
<div id="output"></div>

答案 2 :(得分:0)

HTML:

<div id="output"></div>

JavaScript:

let numbers = [1990, 1991, 1992];

numbers.forEach(function(item) {
  var span = document.createElement("span");
  var text = document.createTextNode(item);
  span.appendChild(text);
  document.getElementById("output").appendChild(span);
});

CSS:

span {
  margin-right: 10px;
}

答案 3 :(得分:0)

尝试以下代码:

let numbers = [1990, 1991, 1992];
let history = [];
let historyContainer = document.getElementById("output");
let para = document.createElement("p");
history.push(numbers.join(" "));
numbers.forEach(function(element){
  console.log(element);
    let text = document.createElement("span");
    let node = document.createTextNode(element);
  text.appendChild(node)
    para.appendChild(text);
  historyContainer.appendChild(para);
});

期望的HTML:

enter image description here