为什么我的 for 循环来一次

Why does my for loop come once?

本文关键字:一次 我的 for 循环 为什么      更新时间:2023-09-26

我的函数中有一个带有循环的代码。

请看一下我的代码:

<!doctype html>
<html>
<head>
    <title>Test</title>
</head>
<body>
    Kies een tafel:
    <select id="tafels">
    <option value="1">Tafel 1</option>
    <option value="2">Tafel 2</option>
    <option value="3">Tafel 3</option>
    <option value="4">Tafel 4</option>
    <option value="5">Tafel 5</option>
    <option value="6">Tafel 6</option>
    <option value="7">Tafel 7</option>
    <option value="8">Tafel 8</option>
    <option value="9">Tafel 9</option>
    <option value="10">Tafel 10</option>
    </select>
    <input type="submit" id="submit" value="bereken" onclick="tafel23();">
    <div id="asd">
    </div>
    <script>
            function tafel23(){
        var value = document.getElementById('tafels').value;
        var value1 = parseInt(value);
        var teller = 0;
        for(teller = 1; teller <= 10; teller++){
            document.getElementById('asd').innerHTML=(value1 + " x " + teller + " = " + teller * value1 + "<br/>");
        }
        }
    </script>
</body>
</html>

当我单击提交按钮时,我的循环出现了一次......但是当我做 innerHTML+= 时,它工作时,整个循环都出现了,但是当我一次又一次地按下提交按钮时,循环正在堆叠。所以我得到的问题是,当我按下提交按钮时,循环会出现,但不会一次又一次。

提前感谢大家!<3

在执行循环之前尝试清除div:

function tafel23(){
    var value = document.getElementById('tafels').value;
    var value1 = parseInt(value);
    //you might check value1 for NaN here
    document.getElementById('asd').innerHTML=""; //clear it out
    for(var teller = 1; teller <= 10; teller++){
        document.getElementById('asd').innerHTML += value1 + " x " + teller + " = " + teller * value1 + "<br/>";
    }
}