您的位置:首页 > Web前端 > JavaScript

javascript实现简易计算器

2009-02-26 17:04 204 查看
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Untitled Document</title>

<script type="text/javascript">

var a=/^/s*|/s*$/g;

function b(){

var ab=this.toString().replace(a,"");

return ab;

}

String.prototype.trim=b;

var num1 = 0;

var num2 = "";

var flag = 1;

var fuhao = "";

function shu(id){

if (flag == 1) {

if (num1 == 0 && id == 0) {

num1 = 0;

}

else {

num1 += id;
result.value = parseFloat(num1);
}

}
else {
if (num2 == "" || num2 == 0) {
result.value = "";
num2 = id;
}
else {
num2 += id;
}
result.value = num2;
}

}

function jia(jiahao){
flag++;
if (num2 == "") {
fuhao1 = jiahao;
}
else {
result.value = suan(fuhao1);
num1 = result.value;
num2 = "";
fuhao1 = jiahao;
}
}

function suan(fu){
var result = 0;
switch (fu) {
case "+":
result = parseFloat(num1) + parseFloat(num2);
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
result = num1 / num2;
break;
}
return result;
}

function dengyu(){
if (num2 != "") {
result.value = suan(fuhao1);
num1 = result.value;
num2 = "";
}
}

function c(){
num1 = 0;
num2 = "";
flag = 1;
fuhao = "";
result.value=0;
}
</script>
</head>
<body>
<table width="170" border="1">
<tr>
<td colspan="4">
<input class="ri" type="text" id="result" size="21" value="0">
</td>
</tr>
<tr>
<td>
<input onclick="shu(this.id)" type="button" id="7" value=" 7 ">
</td>
<td>
<input onclick="shu(this.id)" type="button" id="8" value=" 8 ">
</td>
<td>
<input onclick="shu(this.id)" type="button" id="9" value=" 9 ">
</td>
<td>
<input onclick="jia(this.value.trim())" type="button" id="jia" value=" + ">
</td>
</tr>
<tr>
<td>
<input onclick="shu(this.id)" type="button" id="4" value=" 4 ">
</td>
<td>
<input onclick="shu(this.id)" type="button" id="5" value=" 5 ">
</td>
<td>
<input onclick="shu(this.id)" type="button" id="6" value=" 6 ">
</td>
<td>
<input onclick="jia(this.value.trim())" type="button" id="jian" value=" - ">
</td>
</tr>
<tr>
<td>
<input onclick="shu(this.id)" type="button" id="1" value=" 1 ">
</td>
<td>
<input onclick="shu(this.id)" type="button" id="2" value=" 2 ">
</td>
<td>
<input onclick="shu(this.id)" type="button" id="3" value=" 3 ">
</td>
<td>
<input onclick="jia(this.value.trim())" type="button" id="cheng" value=" * ">
</td>
</tr>
<tr>
<td>
<input onclick="shu(this.id)" type="button" id="0" value=" 0 ">
</td>
<td>
<input onclick="c()" type="button" id="cls" value=" c ">
</td>
<td>
<input onclick="jia(this.value.trim())" type="button" id="chu" value=" / ">
</td>
<td>
<input onclick="dengyu()" type="button" id="deng" value=" = ">
</td>
</tr>
</table>

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: