这是我的HTML代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
Calculator
</title>
<script src="JScript1.js" type="text/javascript"></script>
</head>
<body>
       
<h1> Calculator </h1>
<form>
<input id="txt1" type="text" />
     
<input id="rad1" type="radio" value="add" />add  
<input id="rad2" type="radio" value="mul" />mul  
<input id="rad3" type="radio" value="div" />div  
<input id="rad4" type="radio" value="sub" />sub  
     
<input id="txt2" type="text" />
<button id="mButton" value="Calculate" onclick="calculate()">Calculate!!</button>
</form>
<p id="resultP">Result will be displayed here:</p>
</body>
</html>
这是JavaScript:
function calculate()
{
var first = document.getElementById('txt1').value;
var sec = document.getElementById('txt2').value;
var result;
if (document.getElementById('rad1').checked) {
result = parseInt(first) + parseInt(sec);
}
else if (document.getElementById('rad2').checked) {
result = first * sec;
}
else if (document.getElementById('rad3').checked) {
result = first / sec;
}
else if (document.getElementById('rad4').checked) {
result = first - sec;
}
alert(result);
var resultP = document.getElementById('resultP');
resultP.innerHTML = result;
};
Upto alert(result);
运行正常。但它没有在p标签中设置结果。此外,当我按下Calculate时,整个页面闪烁,并且在两个输入字段中输入的值都消失了。
当我按下Calculate时,地址栏上的链接也会更改为/htmlCode.html?arithematic2=mul
答案 0 :(得分:2)
页面闪烁,因为它重新加载。表单中的默认<button>
类型为submit
。您的JavaScript代码不会阻止提交表单,因此在执行calculate
后,它会重定向到同一页面,将所有表单数据添加到URL中。
您应该将按钮定义为
<button type="button" onclick="calculate()">Calculate</button>
或将calculate
函数附加为表单的submit
事件处理程序并阻止提交,例如使用纯HTML属性:
<form onsubmit="calculate(); return false;">
答案 1 :(得分:1)
试试这个:
<h1> Calculator </h1>
<form>
<input id="txt1" type="text" />
<input type="radio" id="rad1" name="a" value="add" />add
<input type="radio" id="rad2" name="a" value="mul" />mul
<input type="radio" id="rad3" name="a" value="div" />div
<input type="radio" id="rad4" name="a" value="sub" />sub
<input id="txt2" type="text" />
<button id="mButton" value="Calculate" onclick="return calculate()">Calculate!!</button>
</form>
<p>Result will be displayed here: <span id="resultP"></span></p>
function calculate()
{
var first = document.getElementById('txt1').value;
var sec = document.getElementById('txt2').value;
var result;
if (document.getElementById('rad1').checked) {
result = parseInt(first) + parseInt(sec);
}
else if (document.getElementById('rad2').checked) {
result = first * sec;
}
else if (document.getElementById('rad3').checked) {
result = first / sec;
}
else if (document.getElementById('rad4').checked) {
result = first - sec;
}
var resultP = document.getElementById('resultP');
resultP.innerHTML = result;
return false;//this will prevent the default action
}
答案 2 :(得分:0)
这是因为按下事件可以防止这种情况发生,您需要在单击时使事件静音。
function calculate(event) { event.preventDefault() ...
答案 3 :(得分:0)
将此添加到您的按钮,它将正常工作
type='button'