[英]Why does this javascript function stop working?
我这里有一个简单的比较应用程序,它使用2个数字,看哪个更大,然后相应地更改段落的内部HTML。 当我运行它时,它似乎工作正常,但是当我开始在第3或第4次插入新数字时,它停止工作,并开始说数字越小越好。 发生这种情况似乎是随机的。 谁能向我解释为什么会这样?
HTML :
<p>Enter 2 numbers to see which one is highest.</p>
<input type="text" id="firstnumber" class="inputs" class="clearme"/>
<input type="text" id="secondnumber" class="inputs"/>
<input type="button" class="inputs" value="submit" id="button"/>
<p id ="message" style="color: blue;">Answer appears here.</p>
CSS :
.inputs {
float : left;
}
#secondnumber {
clear: both;
}
#button {
clear: left;
}
p {
clear: both;
}
JavaScript :
function myfunction(num1, num2) {
if (num1 > num2) {
document.getElementById("message").innerHTML = "The Higher number is " + num1 + ", which was the first value.";
} else {
document.getElementById("message").innerHTML = "The Higher number is " + num2 + ", which was the second value.";
}
}
document.getElementById('button').onclick = function(){
var x = document.getElementById("firstnumber").value;
var y = document.getElementById("secondnumber").value;
myfunction(x, y);
console.log(x);
console.log(y);
}
非常感谢你。
需要将字符串转换为数字。
Number(Str)
parseInt(Str, 10)
+Str
几种方法是:
function myfunction(num1, num2) { if (num1 > num2) { document.getElementById("message").innerHTML = "The Higher number is " + num1 + ", which was the first value."; } else { document.getElementById("message").innerHTML = "The Higher number is " + num2 + ", which was the second value."; } } document.getElementById('button').onclick = function() { var x = Number(document.getElementById("firstnumber").value); var y = Number(document.getElementById("secondnumber").value); myfunction(x, y); console.log(x); console.log(y); }
.inputs { float: left; } #secondnumber { clear: both; } #button { clear: left; } p { clear: both; }
<p> Enter 2 numbers to see which one is highest. </p> <input type="text" id="firstnumber" class="inputs" class="clearme" /> <input type="text" id="secondnumber" class="inputs" /> <input type="button" class="inputs" value="submit" id="button" /> <p id="message" style="color: blue;"> Answer appears here. </p>
来自输入的值将作为字符串进行比较。
因此,像“ 10”这样的数字将看起来小于“ 2”,因为它们是按字典顺序而不是数字方式进行比较。 您可以通过在比较num1和num2参数时添加+来解决此问题
if (+num1 > +num2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.