简体   繁体   English

为什么此代码卡住了并且不起作用(javascript)

[英]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. 它不适用于任何浏览器或JSFiddle。 The page won't be responsive and gets stuck. 该页面无法响应,并被卡住。

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

Html: 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: 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 编辑: JSlint说没有错误

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. 如果在事件处理程序外部调用initialize'f = first.value',则不会为f分配任何值,因为代码是在加载页面时执行的,而不是在单击Submit按钮之后执行的。 Same goes with 's' and 'ic'. “ s”和“ 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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