用js實現簡易計算器 – Javascript教程_JS教程_技術文章 – 程式設計聯盟

//用js實現簡易計算器完整代碼,大傢看下,不足的地方給下建議
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 <html xmlns="https://www.w3.org/1999/xhtml">
 <head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>簡易計算機</title>
</head>
<body>
<table width="33%" height="193" border="1">
  <tr>
    <td colspan="4"><input type="text" size="50" name="result" id="result"></td>
  </tr>
  <tr>
    <td width="24%"><input type="button" value="     1     "  onclick="getNum(1)"></td>
    <td width="23%"><input type="button" value="     2     " onclick="getNum(2)"></td>
    <td width="26%"><input type="button" value="     3     " onclick="getNum(3)"></td>
    <td width="27%"><input type="button" value="     +     " onclick="getNum('+')"></td>
  </tr>
  <tr>
    <td><input type="button" value="     4     " onclick="getNum(4)"></td>
    <td><input type="button" value="     5     " onclick="getNum(5)"></td>
    <td><input type="button" value="     6     " onclick="getNum(6)"></td>
    <td><input type="button" value="     –     " onclick="getNum('-')"></td>
  </tr>
  <tr>
    <td><input type="button" value="     7     " onclick="getNum(7)"></td>
    <td><input type="button" value="     8     " onclick="getNum(8)"></td>
    <td><input type="button" value="     9     " onclick="getNum(9)"></td>
    <td><input type="button" value="     *     " onclick="getNum('*')"></td>
  </tr>
  <tr>
    <td><input type="button" value="     0     " onclick="getNum(0)"></td>
    <td><input type="button" value="     .     " onclick="getNum('.')"></td>
    <td><input type="button" value="     =     " onclick="getResult()"></td>
    <td><input type="button" value="     /     " onclick="getNum('/')"></td>
  </tr>
</table>
<script type="text/javascript" language="javascript">
//判斷是否清空
var clearContent=false;
//獲得數字
function getNum(num){
if(clearContent){
//如果已經有結果存在則將其清空
document.getElementById("result").value="";
clearContent=false;
}
//獲取結果對象
var objresult=document.getElementById("result");
//實現數字連接
objresult.value+=num;
}
//獲取結果對象值
function getResult(){
var objresult2=document.getElementById("result");
//為結果賦值
objresult2.value=objresult2.value+"="+eval(objresult2.value);
clearContent=true;
}
</script>
</body>
</html>

摘自 席偉娜的專欄

發佈留言