[英]If statement doesnt work? Javascript
I have two textboxes and one button. 我有两个文本框和一个按钮。 I putt numbers in the first textbox and press the button to add the number to a total which is displayed in the second box, till it reaches 1000. But the if statement doesn't work for some reason. 我将数字放在第一个文本框中,然后按按钮以将数字添加到第二个框中显示的总数中,直到达到1000。但是由于某些原因,if语句不起作用。
This works fine: 这很好用:
<html>
<title>Ask7</title>
<script>
var total=0;
function calculate()
{
var box1;
box1=parseFloat(document.getElementById("box1").value);
total=total+box1;
document.getElementById("box2").innerHTML="";
document.getElementById("box2").value=total;
}
</script>
<body>
<h3>Give num:</h3>
<input id="box1" type="text"></input>
<button onclick="calculate()" type="button">ADD</button>
<br>
<h3>Total:</h3>
<input id="box2" readonly="readonly" type="text"></input>
</body>
</html>
This doesn't: 这不是:
<html>
<title>Ask7</title>
<script>
var total=0;
function calculate()
{
if(total<1000)
{
var box1;
box1=parseFloat(document.getElementById("box1").value);
total=total+box1;
document.getElementById("box2").innerHTML="";
document.getElementById("box2").value=total;
}
else
{
alert("OVER 1000!");
break;
}
}
</script>
<body>
<h3>Give num:</h3>
<input id="box1" type="text"></input>
<button onclick="calculate()" type="button">ADD</button>
<br>
<h3>Total:</h3>
<input id="box2" readonly="readonly" type="text"></input>
</body>
</html>
Basically I don't get why the if statement doesn't work. 基本上我不明白为什么if语句不起作用。
Remove the break
, it doesn't belong there. 删除break
,它不属于该break
。
I think you should have your code like this: 我认为您应该具有如下代码:
var total = 0;
function calculate() {
var box1;
box1 = parseFloat(document.getElementById("box1").value);
total = total + box1;
box2 = document.getElementById("box2");
box2.value = total;
if (total < 1000) {
// do something
} else {
alert("OVER 1000!");
// break;
box2.value = 0; // to clean the value after 1000
}
}
...
else {
alert("OVER 1000!");
box2.value = 0; // to clean the value after 1000
total = 0; // **** also reset the global var for reuse as still adding over 1000
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.