JavaScript简单计算器
时间:2010-09-12 来源:ChangVH
<html>
<head>
<script language="javascript">
function cal(str)
{
var a = parseInt(document.form1.a.value);
var b = parseInt(document.form1.b.value);
if(str == "+")
{
document.form1.c.value = a + b;
}
else if(str == "-")
{
document.form1.c.value = a - b;
}
else if(str == "*")
{
document.form1.c.value = a * b;
}
else if(str == "/")
{
document.form1.c.value = a / b;
}
}
</script>
</head>
<body>
<form name="form1" action="">
a:<input type="text" name="a" style="width:210px"/><br>
b:<input type="text"name="b" style="width:210px" /><br>
<input type="button" name="sum" onClick="cal('+')" id= "sum" value="+" style="width:50px"/>
<input type="button" name="sub" onClick="cal('-')" id= "sub" value="-" style="width:50px"/>
<input type="button" name="mul" onClick="cal('*')" id= "mul" value="*" style="width:50px"/>
<input type="button" name="div" onClick="cal('/')" id= "div" value="/" style="width:50px"/><br>
c:<input id="c" type="text" name="c" style="width:210px" />
</form>
</body>
</html>
上面是第一种方法
下面是第二种
<html>
<head>
<script language="javascript">
function cal(value)
{
var a = parseInt(document.form1.a.value);
var b = parseInt(document.form1.b.value);
switch(value)
{
case '+':
document.form1.c.value = a + b;
break;
case '-':
document.form1.c.value = a - b;
break;
case '*':
document.form1.c.value = a * b;
break;
case '/':
document.form1.c.value = a / b;
break;
}
}
</script>
</head>
<body>
<form name="form1" action="#">
a:<input type="text" name="a" style="width:210px"/><br>
b:<input type="text"name="b" style="width:210px" /><br>
<input type="button" name="sum" onClick="cal('+')" value="+" style="width:50px"/>
<input type="button" name="sub" onClick="cal('-')" value="-" style="width:50px"/>
<input type="button" name="mul" onClick="cal('*')" value="*" style="width:50px"/>
<input type="button" name="div" onClick="cal('/')" value="/" style="width:50px"/><br>
c:<input type="text" name="c" style="width:210px" />
</form>
</body>
</html>