简体   繁体   English

For循环仅输出最后一次迭代

[英]For loop only outputs last iteration

I am new to Javascript and am just playing around trying to print a simple for loop to the HTML. 我是Java的新手,只是在尝试将简单的for循环打印到HTML。

HTML: HTML:

<div id="hello"</div>

JS : JS:

var text="";

for (var i=0;i<10;i++) {
    document.getElementById("hello").innerHTML=text+i;
}

My problem is that this code only outputs the last iteration '9', and not '0123456789' which is what I want. 我的问题是此代码仅输出最后的迭代“ 9”,而不是我想要的“ 0123456789”。

Now if i do document.write it prints out the numbers fine but I heard this is bad practice so I just want to do it the correct way. 现在,如果我执行document.write它可以很好地打印出数字,但是我听说这是一种不好的做法,所以我只想以正确的方式进行操作。

Thanks 谢谢

It would be better to build your text content first and insert it into HTML element once (to save some time): 最好先构建您的文本内容,然后将其插入HTML元素一次(以节省时间):

var text="";

for (var i=0;i<10;i++) {
    text += i;
}

document.getElementById("hello").innerHTML = text;

You should use the addition assignment operator += that adds a value to a variable, so you're just missing + before = in : 你应该使用加法赋值运算符+= ,增加了一个值的变量,所以你只是缺少+之前=在:

document.getElementById("hello").innerHTML += text+i;

NOTE : Use textContent instead of innerHTML because you're appending just a text, check example bellow. 注意:使用textContent而不是innerHTML因为您仅添加文本,请检查下面的示例。


 var text=""; for (var i=0;i<10;i++) { document.getElementById("hello").textContent += text+i; } 
 <div id="hello"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM