2013-03-20 118 views
0

我正在使用JavaScript创建我的第一个Web项目。我不知道如何正确使用循环。我试图得到这样的结果:For循环和追加

text 
text 
text 
text 

但我得到这个:

text 

这就是代码:

for (i = 0; i <= 5; 1++) { 
$("#sth").append("text" + "<br>"); 
} 

小提琴链接:http://jsfiddle.net/6K7Ja/

我只是开始学习JavaScript。帮助将不胜感激:)

+0

你拨弄甚至没有获得单行“文本”,因为语法错误。这是一个“错字问题”,应该可能会被关闭。 – Pointy 2013-03-20 15:26:10

+2

并永远不会向DOM重复添加连续重复的内容。尝试var html + =“text”+“
”;并在最后做一个追加。 – theshadowmonkey 2013-03-20 15:26:11

+0

你有一个错字,用'i ++'替换'1 ++' – 2013-03-20 15:26:24

回答

9

您的代码有1++它应该是i++

3
var text = ""; 
for (var i = 0; i < 4; i++) { 
    text += "text<br>"; 
} 
$("#sth").append(text); 
2

你想追加出循环。将值添加到变量,然后追加该变量一次。当你这样做的时候会发生什么,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); 

你可以看到在这个Fiddle合作,并发挥与它周围。

下面是一些阅读材料,你应该检查出:

http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly