简体   繁体   中英

Why does this codes stuck and doesn't work (javascript)

This simple code makes me crazy. It doesn't work in any browser or JSFiddle. The page won't be responsive and gets stuck.

https://jsfiddle.net/dckkj4uu/6/

Html:

<html>
    <head>
        <title>Page Title</title>
    </head>
    <body>
    <p>
    First number:<br>
        <input type="number" id="fir">
        <br>
    Second number:<br>        
        <input type="number" id="sec">
        <br>
    Increment:<br>        
        <input type="number" id="inc">
        <br>        
    </p>
        <button id="btn">Click</button>
    </body>
</html>

JS:

document.getElementById("btn").addEventListener("click", me);


var first = document.getElementById("fir");
var f = first.value;
var second = document.getElementById("sec");
var s = second.value;
var inc = document.getElementById("inc");
var ic = inc.value;

var str = "";

function me(){
    for(var i=f; i<=s; i=i+ic){

        str+=i;

    }
return document.write(str);}

It always crashes

Edit: JSlint says no error

If you call initialize 'f = first.value' outside the event handler there won't be any value assigned to f because the code executes when the page is loaded, not after you've clicked on the submit button. Same goes with 's' and 'ic'.

This should fix the issue:

function me(){
    var f = parseInt(first.value);
    var s = parseInt(second.value);
    var ic = parseInt(inc.value);
    for(var i = f; i <= s; i = i + parseInt(inc.value)) {
        str += i;
    }
    return document.write(str);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM