法一
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.box{width: 400px;margin: 100px auto;}
.box .c_t{font: 20px sans-serif;}
.box .c_1{height: 20px;line-height: 20px;margin-top: 10px;}
</style>
<script type="text/javascript">
function add(){
//form的name.input的name就可
//取到dom对象
var a = document.myform.txt1.value;
var b = document.myform.txt2.value;
var c = parseInt(a)+parseInt(b);
document.myform.sum.value = c;
}
function jian(){
//form的name.input的name就可
//取到dom对象
var a = document.myform.txt1.value;
var b = document.myform.txt2.value;
var c = parseInt(a)-parseInt(b);
document.myform.sum.value = c;
}
function chen(){
//form的name.input的name就可
//取到dom对象
var a = document.myform.txt1.value;
var b = document.myform.txt2.value;
var c = parseInt(a)*parseInt(b);
document.myform.sum.value = c;
}
function chu(){
//form的name.input的name就可
//取到dom对象
var a = document.myform.txt1.value;
var b = document.myform.txt2.value;
var c = parseInt(a)/parseInt(b);
document.myform.sum.value = c;
}
</script>
</head>
<body>
<form name="myform">
<div class="box">
<div class="c_t">
购物简易计算器
</div>
<div class="c_1">
第一个数:<input type="text" name="txt1" placeholder="---请输入第一个数---"/>
</div>
<div class="c_1">
第一个数:<input type="text" name="txt2" placeholder="---请输入第一个数---"/>
</div>
<div class="c_1">
<!-- onclick鼠标单击事件 -->
<input type="button" value="+" onclick="add()"/>
<input type="button" value="-" onclick="jian()"/>
<input type="button" value="*" onclick="chen()"/>
<input type="button" value="/" onclick="chu()"/>
</div>
<div class="c_1">
结 果:<input type="text" name="sum" value="" />
</div>
</div>
</form>
</body>
法二
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.box{width: 400px;margin: 100px auto;}
.box .c_t{font: 20px sans-serif;}
.box .c_1{height: 20px;line-height: 20px;margin-top: 10px;}
</style>
<script type="text/javascript">
function getSum(flag){
//取到dom对象
var a = parseInt(document.getElementById("txt1").value);
var b = parseInt(document.getElementById("txt2").value);
var c =0;
switch(flag){
case 1:
c = a+b;
break;
case 2:
c = a-b;
break;
case 3:
c = a*b;
break;
case 4:
c = a/b;
break;
}
document.getElementById("txtsum").value = c;
}
</script>
</head>
<body>
<form name="myform">
<div class="box">
<div class="c_t">
购物简易计算器
</div>
<div class="c_1">
第一个数:<input type="text" name="txt1" id="txt1" placeholder="---请输入第一个数---"/>
</div>
<div class="c_1">
第一个数:<input type="text" name="txt2" id="txt2" placeholder="---请输入第一个数---"/>
</div>
<div class="c_1">
<!-- onclick鼠标单击事件 -->
<input type="button" value="+" onclick="getSum(1)"/>
<input type="button" value="-" onclick="getSum(2)"/>
<input type="button" value="*" onclick="getSum(3)"/>
<input type="button" value="/" onclick="getSum(4)"/>
</div>
<div class="c_1">
结 果:<input type="text" id="txtsum" name="sum" value="" />
</div>
</div>
</form>
</body>
</html>