DIV CSS 佈局教程網

用幾個按鈕就能跑的 JavaScript 簡易計算器
編輯:關於JavaScript     

這個計算器只用了 HTML 表單與少量 JavaScript,介面樸素,但結構清楚,適合拿來改造成自己想要的樣子。

<!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>javascript簡單計算器</title>
</head>
<body>
<form name="calc">
<input type="text" name="expr" size="30" action="compute(this.form)" />
<input type="button" value=" 7 " onclick="enter(this.form,seven)" />
<input type="button" value=" 8 " onclick="enter(this.form,eight)" />
<input type="button" value=" 9 " onclick="enter(this.form,nine)" />
<input type="button" value=" / " onclick="enter(this.form,divide)" />
<input type="button" value=" 4 " onclick="enter(this.form,four)" />
<input type="button" value=" 5 " onclick="enter(this.form,five)" />
<input type="button" value=" 6 " onclick="enter(this.form,six)" />
<input type="button" value=" * " onclick="enter(this.form,multiply)" />
<input type="button" value=" 1 " onclick="enter(this.form,one)" />
<input type="button" value=" 2 " onclick="enter(this.form,two)" />
<input type="button" value=" 3 " onclick="enter(this.form,three)" />
<input type="button" value=" - " onclick="enter(this.form,minus)" />
<input type="button" value=" 0 " onclick="enter(this.form,zero)" />
<input type="button" value=" . " onclick="enter(this.form,decimal)" />
<input type="button" value=" + " onclick="enter(this.form,plus)" />
<input type="button" value=" = " onclick="compute(this.form)" />
<input type="button" value="AC" onclick="form.reset()"/>
</form>
</body>
</html>

每個數字鍵呼叫 enter(form, 對應的值),把字元追加到輸入框;等號呼叫 compute 求值;AC 則直接 form.reset() 清空。要美化,只要改按鈕的 CSS 與排列(例如換成 grid 佈局)即可,邏輯完全不用動。

關於 eval()

這類計算器的 compute 通常靠 eval() 求值,所以值得說明它的行為。

定義與用法: eval() 會計算某個字串並執行其中的 JavaScript 程式碼。

回傳值: 運算 string 所得到的值(如果有的話)。

注意事項: 該方法只接受原始字串作為參數,若傳入的不是原始字串,會原封不動地回傳,因此不要傳 String 物件給它。若嘗試覆寫 eval 屬性、或把 eval() 指派給另一個屬性再呼叫,ECMAScript 實作允許拋出 EvalError。

例外情況: 參數中沒有合法的運算式與語句時拋出 SyntaxError;非法呼叫 eval() 時拋出 EvalError;若傳入的程式碼本身產生例外,eval() 會把該例外原樣拋給呼叫者。

提醒: eval() 功能雖然強大,實際開發中真正需要的場合並不多。尤其在計算器這種直接吃使用者輸入的場景,改用小規模的運算式解析器會安全得多——使用者輸入什麼就執行什麼,本身就是風險來源。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved