我有两个文本框和一个按钮。我在第一个文本框中输入数字并按下按钮将数字添加到第二个框中显示的总数,直到达到1000.但if语句由于某种原因不起作用。
这很好用:
<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>
这不是:
<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>
基本上我不明白为什么if语句不起作用。
答案 0 :(得分:1)
删除break
,它不属于那里。
我认为你的代码应该是这样的:
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
}
}
答案 1 :(得分:0)
...
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
}