<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv = "content-type" content="text/html;charset=utf-8"/>
<script src="js.js" type="text/javascript" language="javascript">
</script>
</head>
<body>
<form>
<input type="button" value="1" onclick = "cal(this.value);"/> <!--調用函數-->
<input type="button" value="2" onclick = "cal(this.value);"/>
<input type="button" value="3" onclick = "cal(this.value);"/>
<input type="button" value="4" onclick = "cal(this.value);"/>
<input type="button" value="+" onclick = "cal(this.value);"/>
<input type="button" value="-" onclick = "cal(this.value);"/>
<input type="button" value="*" onclick = "cal(this.value);"/>
<input type="button" value="/" onclick = "cal(this.value);"/>
<input type="button" value="=" onclick = "cal(this.value);"/><br />
<input type = "text" id = "text" name = "text" />
</form>
</body>
</html>
///js.js
function cal(value){ var text = document.getElementById("text").value; var last = text.charAt(text.length-1);// 獲得文本框中的最後一個元素 if(text == null){ text = ""; }else{ if((value == "+")||(value == "-")||(value == "*")||(value == "/")){//輸入的是 + - / * if((last == "+")||(last == "-")||(last == "*")||(last == "/")){//文本框中的最後一個元素是 + - * / 在輸入 + - / * 時提示出錯 alert("輸入不正確"); }else{//文本框中的最後一個元素是 + - * / 再輸入數字時會添加到後面 text += value; } }else if(value == "="){//輸入的是= if((last == "+")||(last == "-")||(last == "*")||(last == "/")){ //輸入的是= , 當最後一個元素是+ - * / 時, 不能計算 ,只顯示除最後符號號的數 text = text.substring(0,text.length-1); }else{//輸入的是= 最後一個是數字 可以計算 text = eval(text); ///使用eval(str) 計算 } }else{//輸入的是數字 直接顯示 text += value; } } document.getElementById("text").value = text; //將最後結果返回給文本框 }