为什么此代码卡住且不起作用 (javascript)
Why does this codes stuck and doesn't work (javascript)
这个简单的代码让我抓狂。
它不适用于任何浏览器或 JSFiddle。该页面将无法响应并卡住。
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);}
总是崩溃
编辑: JSlint 说没有错误
如果您在事件处理程序外部调用初始化 'f = first.value',则不会为 f 分配任何值,因为代码在页面加载时执行,而不是在您单击提交按钮后执行。 's' 和 'ic'.
也是如此
这应该可以解决问题:
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);
}
这个简单的代码让我抓狂。 它不适用于任何浏览器或 JSFiddle。该页面将无法响应并卡住。
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);}
总是崩溃
编辑: JSlint 说没有错误
如果您在事件处理程序外部调用初始化 'f = first.value',则不会为 f 分配任何值,因为代码在页面加载时执行,而不是在您单击提交按钮后执行。 's' 和 'ic'.
也是如此这应该可以解决问题:
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);
}