javascript For 循环和追加
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15527699/
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
For loop and append
提问by alesko007
I'm making my first web project in JavaScript. I don't know how to use for loop properly. I'm trying to get this result:
我正在用 JavaScript 制作我的第一个 Web 项目。我不知道如何正确使用 for 循环。我试图得到这个结果:
text
text
text
text
But I get this:
但我明白了:
text
And that's the code:
这就是代码:
for (i = 0; i <= 5; 1++) {
$("#sth").append("text" + "<br>");
}
Fiddle link: http://jsfiddle.net/6K7Ja/
小提琴链接:http: //jsfiddle.net/6K7Ja/
I just started learning JavaScript. Help will be greatly appreciated :)
我刚开始学习 JavaScript。帮助将不胜感激:)
回答by Pointy
Your code has 1++
where it should be i++
.
您的代码已1++
在应有的位置i++
。
回答by Matt Cain
var text = "";
for (var i = 0; i < 4; i++) {
text += "text<br>";
}
$("#sth").append(text);
回答by Jonny Sooter
You want the append out of the loop. Add the values to a variable then append that variable once. What happens when you do it how you are now, is jQuery will do that append method each time it goes through that loop. That's bad because it will keep doing it every timeand slowing you down. It's better to go through the loop and save what you want to append to a variable. Then just append that variable once. Something like this should do the trick:
您希望 append 退出循环。将值添加到变量,然后附加该变量一次。当您按照现在的方式进行操作时会发生什么,jQuery 将在每次通过该循环时执行该 append 方法。这很糟糕,因为它每次都会继续这样做并减慢你的速度。最好遍历循环并保存要附加到变量的内容。然后只需附加该变量一次。像这样的事情应该可以解决问题:
var appendText = []; //We can define an array here if you need to play with the results in order or just use a string otherwise.
for (var i = 0; i < 4; i++) {
appendText.push("text" + "<br>"); //This adds each thing we want to append to the array in order.
}
//Out here we call the append once
//Since we defined our variable as an array up there we join it here into a string
appendText.join(" ");
$("#sth").append(appendText);
You can see this working in this Fiddleand play around with it.
Here's some reading materials you should check out:
以下是您应该查看的一些阅读材料:
http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly
http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly