javaScript-计算器
calculator.html文件:
<!DOCTYPE html PUBLIC "">
<html>
<head>
<style type="text/css">
#dy { color:000000;background:#ffffff; height:100px; width:200px; }
</style>
<title>计数器</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<script language="javascript" src="calculator.js"></script>
</head>
<body>
<input type="button" value="." onclick="calculater(this.value);" />
<br />
<input type="button" value="0" onclick="calculater(this.value);" />
<input type="button" value="1" onclick="calculater(this.value);" />
<input type="button" value="2" onclick="calculater(this.value);" />
<input type="button" value="3" onclick="calculater(this.value);" />
<input type="button" value="4" onclick="calculater(this.value);" />
<br />
<input type="button" value="+" onclick="calculater(this.value);" />
<input type="button" value="-" onclick="calculater(this.value);" />
<input type="button" value="*" onclick="calculater(this.value);" />
<input type="button" value="/" onclick="calculater(this.value);" />
<input type="button" value="C" onclick="calculater(this.value);" />
<br />
<input type="button" id="dy" value="=" onclick="calculater(this.value);" /><br />
<input type="text" id="txtNumber" />
<span>=</span>
<input type="text" id="result" />
calculator.js文件:
function calculater(s){
var r = 0;
var num = "0123456789.";
var symbol = "+-*/";
var trim = "C";
var txtName = "txtNumber"
//alert(symbol.indexOf(s))
//var fGetElementValue = new Function("name","document.getElementById(name).value;")
//var s1 = document.getElementById("txtNumber").value;
var str1 = document.getElementById(txtName).value;
//var reg = /^\d$/;
//str = str1.replace(/[a-z]/gi,"");
str = str1.replace(/[^0-9\+\-\*\/]/gi,"");
str = str.replace(/^0+/gi,"");
document.getElementById(txtName).value = str;
var strArray = str.split("");
var strArrayLength = strArray.length;
if(num.indexOf(s) >= 0){//数字
document.getElementById(txtName).value +=s;
}
else if(symbol.indexOf(s) >= 0){//运算符号
var lastInput = strArray[strArrayLength-1];
if (symbol.indexOf(lastInput) >= 0){
strArray[strArrayLength-1] = s;
document.getElementById(txtName).value = strArray.join("");
}
else {
document.getElementById(txtName).value +=s;
}
}
else if(trim.indexOf(s) >= 0){//清0
document.getElementById("txtNumber").value = 0
document.getElementById("result").value = ""
}
if(s == "="){
r = eval(document.getElementById("txtNumber").value);
document.getElementById("result").value = r;
}
}
本文出自 “卡特” 博客,请务必保留此出处http://carter.blog.51cto.com/9087165/1637582
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。