Javascript 数组和innerHTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26316536/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript array and innerHTML
提问by Spoofy
I'm just started with JavaScript and I have a little problem.
我刚开始使用 JavaScript,我有一个小问题。
How do I use the innerHTML
propriety to change the text in this element:
我如何使用innerHTML
属性来更改此元素中的文本:
(function showArray(){
var names = new Array("Bob ","Alice ","Ceaser ","David");
names.sort();
for (var i = 0; i < names.length; i++) {
document.getElementById("loop").innerHTML = names[i];
// I'm only getting "David" as output!!
}
})();
<p id="loop">David Alice Bob Ceaser</p>
回答by Dave Chen
Try this, you just need to join the names too.
试试这个,你只需要加入名字。
function showArray() {
var names = new Array("Bob ", "Alice ", "Ceaser ", "David");
names.sort();
document.getElementById("loop").innerHTML = names.join(" ");
}
showArray();
<p id="loop">David Alice Bob Ceaser</p>
回答by KooiInc
Just for the record: your code can be reduced to
仅供记录:您的代码可以简化为
(function() {
document.querySelector("#loop").innerHTML =
["Bob ", "Alice ", "Ceaser ", "David"].sort().join(" ");
}())
<p id="loop"></p>
回答by Oriol
In this case, better use Array.prototype.join
as suggested in @DaveChen's answer.
在这种情况下,最好Array.prototype.join
按照@DaveChen 的回答中的建议使用。
However, you can't always use that. For those cases:
但是,您不能总是使用它。对于这些情况:
- DOM operations are slow. Therefore,
- Don't use
getElementById
inside a loop. Instead, store the element in a variable before the loop. - Don't modify
innerHTML
at each iteration. Instead, update a string variable and only modifyinnerHTML
after the loop.
- Don't use
- Creating arrays using
[]
is faster than withArray
constructor, and it's shorter.
- DOM 操作很慢。所以,
- 不要
getElementById
在循环内使用。相反,在循环之前将元素存储在变量中。 - 不要
innerHTML
在每次迭代时修改。相反,更新字符串变量并仅innerHTML
在循环后修改。
- 不要
- 使用创建数组
[]
比使用Array
构造函数更快,而且时间更短。
However, note that using innerHTML
may produce html injection. If you just want to add text, better use textContent
instead.
但是,请注意,使用innerHTML
可能会产生 html 注入。如果您只想添加文本,最好textContent
改用。
(function showArray(){
var names = ["Bob ","Alice ","Ceaser ","David"],
el = document.getElementById("loop"),
html = '';
names.sort();
for (var i = 0; i < names.length; i++) html += names[i];
el.textContent = html;
})();
<p id="loop">David Alice Bob Ceaser</p>