[英]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.