如何使用按钮控制循环中的迭代次数?

时间:2016-05-07 19:10:02

标签: javascript loops for-loop button

我想用点击按钮来控制循环的迭代。

例如,以下代码只需单击一下即可打印出来:

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4

HTML

<h1>Controlling loop iterations with "Click"</h1>    
<button type="submit" style="width: 80px" name="submit" onclick="main()">Submit</button>
<p id="text"></p>

的JavaScript

function main() {
    document.getElementById("text").innerHTML = loopFunction();
}

function loopFunction() {
    var text = "";
    var i = 0;
    while (i < 5) {
        text += "<br>The number is " + i;
        i++;
    }

    return text;
}

我想点击&#34;提交&#34;按钮并一次运行循环一次迭代(步骤):

例如:

click "submit" = The number is 0
click "submit" = The number is 1
click "submit" = The number is 2
click "submit" = The number is 3
click "submit" = The number is 4

4 个答案:

答案 0 :(得分:0)

像这样更改你的功能。

function loopFunction() {
    var text = "";
    var i = loopFunction.cachedValue ? loopFunction.cachedValue : 0;
    var max = 5;

    if(loopFunction.cachedValue >= max){
       return false;
    }

    text += "<br>The number is " + i;

    if(!loopFunction.cachedValue){
        loopFunction.cachedValue = 0;
    }

    loopFunction.cachedValue++;

    return false;
}

答案 1 :(得分:0)

无需使用循环。将i 置于外部功能,将增量设置为 功能。将i设置为0,设置为,大​​于5。

var text = document.getElementById("text");
var i = 0;
function main() {
    text.innerHTML += "The number is " + i + "<br>";
    if(i > 5) {
        i = 0;
        text.innerHTML = "The number is " + i + "<br>";
    }
    i += 1;
}

JSFiddle

答案 2 :(得分:0)

如果你想要完成的只是一次进行一次迭代,为什么要迭代呢?

您只需使用全局variable即可保留计数值。

&#13;
&#13;
var count = 0;
        
function main() {
    var textElement = document.getElementById("text");

    if (count >= 5) {
        count = 0;
        textElement.innerHTML = "";
    }

    textElement.innerHTML += "<br>" + "The number is " + count++;
}
&#13;
<button type="submit" style="width: 80px" name="submit" onclick="main();">Submit</button>
<p id="text"></p>
&#13;
&#13;
&#13;

每次点击都会给你The number is X;如上面的代码段所示。

除非我误解了你的难题,否则这似乎是你正在寻找的解决方案。

答案 3 :(得分:0)

您可以使用生成器功能。

    function* loopFunction() {
        var i = 0;

        while (i < 5) {
            yield "<br>The number is " + i;
            i++;
        }
    }
    var iterator=loopFunction(); // init generator; no return
    function main(){
        var res=iterator.next(); // returns {value:<result>,done:false|true}
        if(!res.done)
            document.getElementById('text').innerHTML+=res.value;
        else
            document.getElementById('text').innerHTML+='<br />No more results';
        return false;
    }

    <button type="submit" style="width: 80px" name="submit" onclick="return main()">Submit</button> 
<!--"return" is important to avoid submission -->
    <p id="text"></p>