Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript/For循环/基本代码/仅运行一次_Javascript_Loops_For Loop - Fatal编程技术网

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节点的全部内容,因此最终只能看到最后一个(每次迭代都会覆盖上一个)