JavaScript脚本特效编程给力起飞
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人

1.3 简单的计算器

下面,请读者同笔者一起分享一个经典的JavaScript代码,即做一个计算器,如图1-25所示。

图1-25 计算器

这个计算器使用网页浏览器打开即可使用,十分方便,读者可以先尝试看看它的结构。其代码如下,加入任意网页代码的<body>区域中即可。

<script language="javascript">
<!-- Hide the script from old browsers --
function compute(obj)           //单击等于"="按钮调用的函数;
{obj.expr.value = eval(obj.expr.value)} )  //用js的eval()方法计算name为expr中的公式
var one = '1'               //定义变量;
var two = '2'
var three = '3'
var four = '4'
var five = '5'
var six = '6'
var seven = '7'
var eight = '8'
var nine = '9'
var zero = '0'
var plus = '+'
var minus = '-'
var multiply = '*'
var divide = '/'
var decimal = '.'
function enter(obj, string)              //type="button"的调用函数
  {obj.expr.value += string}            //在表单expr的值后面连上相应的字符
function clear(obj)
  {obj.expr.value = ''}                 //清空表单
// --End Hiding Here -->
</script>
<form name="calc">
<table border=1>
<td colspan=4><input type="text" name="expr" size=30 action="compute(this.form)">
<tr>
<td><input type="button" value="  7  " onClick="enter(this.form, seven)">
<td><input type="button" value="  8  " onClick="enter(this.form, eight)">
<td><input type="button" value="  9  " onClick="enter(this.form, nine)">
<td><input type="button" value="  /  " onClick="enter(this.form, divide)">
<tr><td><input type="button" value="  4  " onClick="enter(this.form, four)">
<td><input type="button" value="  5  " onClick="enter(this.form, five)">
<td><input type="button" value="  6  " onClick="enter(this.form, six)">
<td><input type="button" value="  *  " onClick="enter(this.form, multiply)">
<tr><td><input type="button" value="  1  " onClick="enter(this.form, one)">
<td><input type="button" value="  2  " onClick="enter(this.form, two)">
<td><input type="button" value="  3  " onClick="enter(this.form, three)">
<td><input type="button" value="  -  " onClick="enter(this.form, minus)">
<tr><td colspan=2><input type="button"value="  0  "onClick="enter(this.form,zero)">
<td><input type="button" value="  .  " onClick="enter(this.form, decimal)">
<td><input type="button" value="  +  " onClick="enter(this.form, plus)">
<tr><td colspan=2><input type="button"value="  =  "onClick="compute(this.form)">
<td colspan=2><input type="button" value="AC" size= 3 onClick="clear(this.form)">
</table>
</form>