Javascript/For循环/基本代码/仅运行一次
首先,是的,我看过很多关于这个主题的代码,没有一个像我的。我有一个非常基本的代码,所以我很抱歉,如果我错过了一些明显的,但我不能理解为什么我的代码将只显示一个数字 这是代码Javascript/For循环/基本代码/仅运行一次,javascript,loops,for-loop,Javascript,Loops,For Loop,首先,是的,我看过很多关于这个主题的代码,没有一个像我的。我有一个非常基本的代码,所以我很抱歉,如果我错过了一些明显的,但我不能理解为什么我的代码将只显示一个数字 这是代码 <!DOCTYPE html> <head> </head> <body> <div id="test"></div> <script> var wildCard = (Math.floor(Math.random() * 5) + 1);
<!DOCTYPE html>
<head>
</head>
<body>
<div id="test"></div>
<script>
var wildCard = (Math.floor(Math.random() * 5) + 1);
var temp = 1;
for (var i=0; i < 5; i++){
document.getElementById("test").innerHTML = wildCard + "<br />";
temp++;
}
</script>
</body>
</html>
var通配符=(Math.floor(Math.random()*5)+1);
var-temp=1;
对于(变量i=0;i<5;i++){
document.getElementById(“test”).innerHTML=通配符+“
”;
temp++;
}
非常基本的代码,但是唯一的一件事是,我只得到一个随机数打印,而不是5在垂直线下降。我想知道我遗漏了什么,为什么它不会循环 在循环的每次迭代中生成一个新的随机数,然后在循环完成后分配一次完整的HTML
<script>
var temp = 1;
var html = "";
for (var i=0; i < 5; i++) {
var wildCard = (Math.floor(Math.random() * 5) + 1);
html += wildCard + "<br/>";
temp++;
}
document.getElementById("test").innerHTML = html;
</script>
var-temp=1;
var html=“”;
对于(变量i=0;i<5;i++){
var通配符=(Math.floor(Math.random()*5)+1);
html+=通配符+“
”;
temp++;
}
document.getElementById(“test”).innerHTML=html;
之所以只打印一个数字而不是五个,是因为id为test
的DOM节点的内部html在每次迭代中都会被替换。当for循环结束时,您只能看到最后一次迭代的值
您可以使用createTextNode
和appendChild
按如下方式完成此任务:
var temp = 1;
for (var i=0; i < 5; i++){
const wildCard = (Math.floor(Math.random() * 5) + 1);
const textNode = document.createTextNode(wildCard);
const testDiv = document.getElementById("test");
testDiv.appendChild(textNode)
testDiv.appendChild(document.createElement("br"));
temp++;
}
var-temp=1;
对于(变量i=0;i<5;i++){
常量通配符=(Math.floor(Math.random()*5)+1);
const textNode=document.createTextNode(通配符);
const testDiv=document.getElementById(“测试”);
testDiv.appendChild(textNode)
testDiv.appendChild(document.createElement(“br”));
temp++;
}
每次执行循环时,都会替换DOM节点的全部内容,因此最终只能看到最后一个(每次迭代都会覆盖上一个)