【问题标题】:For loop and append [closed]For循环和追加[关闭]
【发布时间】:2013-03-09 19:01:13
【问题描述】:

我正在用 JavaScript 制作我的第一个 Web 项目。我不知道如何正确使用 for 循环。我试图得到这个结果:

text
text
text
text

但我明白了:

text

这就是代码:

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

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

我刚开始学习 JavaScript。非常感谢您的帮助:)

【问题讨论】:

  • 由于语法错误,您的小提琴甚至没有得到单行“文本”。这是一个“错字问题”,应该关闭。
  • 并且永远不要将连续重复的东西附加到 DOM 中。试试 var html += "text" + "
    ";最后做一个追加。
  • 你打错了,把1++换成i++

标签: javascript jquery loops for-loop append


【解决方案1】:

你的代码有1++,它应该是i++

【讨论】:

    【解决方案2】:
    var text = "";
    for (var i = 0; i < 4; i++) {
        text += "text<br>";
    }
    $("#sth").append(text);
    

    【讨论】:

      【解决方案3】:

      您希望追加退出循环。将值添加到变量,然后附加该变量一次。当您按照现在的方式执行此操作时会发生什么,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

      【讨论】:

      • 这对我帮助很大:)
      猜你喜欢
      • 2014-02-08
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 2016-11-30
      • 2013-09-22
      相关资源
      最近更新 更多