为什么我的for循环来了一次?

时间:2014-12-06 15:33:31

标签: javascript html

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

请查看我的代码:

<!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 + =而不是它的工作时,整个循环就出现了,但是当我一次又一次按下提交按钮时,循环正在堆叠.. 所以我遇到的问题是,当我按下提交按钮时会出现循环,但不是一次又一次..

先谢谢你们!&lt; 3

1 个答案:

答案 0 :(得分:2)

在执行循环之前尝试清除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/>";
    }
}