码迷,mamicode.com
首页 > Web开发 > 详细

JS之面向对象

时间:2017-02-10 15:41:24      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:pac   type   script   sum   var   htm   i++   cli   length   

用面向对象方法做一个计算器:

html代码:

<style type="text/css">
table{
margin: 0 auto;
text-align: center;
}
input{
width: 100px;
height: 80px;
font-size: 60px;
}
#sum{
width: 480px;
}

</style>

<body>
<table width="500" height="600" border="1" cellpadding="0" cellspacing="2">
<tr >
<td colspan="4">
<input type="text" id="sum"/>
</td>

</tr>
<tr >
<td><input type="button" value="1" id="num1" name="num"/></td>
<td><input type="button" value="2" id="num2" name="num"/></td>
<td><input type="button" value="3" id="num3" name="num"/></td>
<td><input type="button" value="+" id="fuhao1" name="fuhao"/></td>


</tr>
<tr >
<td><input type="button" value="4" id="num4" name="num"/></td>
<td><input type="button" value="5" id="num5" name="num"/></td>
<td><input type="button" value="6" id="num6" name="num"/></td>
<td><input type="button" value="-" id="fuhao2" name="fuhao"/></td>

</tr>
<tr >
<td><input type="button" value="7" id="num7" name="num"/></td>
<td><input type="button" value="8" id="num8" name="num"/></td>
<td><input type="button" value="9" id="num9" name="num"/></td>
<td><input type="button" value="*" id="fuhao3" name="fuhao"/></td>

</tr>
<tr height="100">

<td> <input type="button" value="0" id="num0" name="num"/></td>
<td> <input type="button" value="." id="num." name="num"/></td>
<td> <input type="button" value="=" id="dengyu" name="dengyu"/></td>
<td> <input type="button" value="/" id="fuhao4" name="fuhao"/></td>

</tr>
</table>
</body>

<script src="js/counter.js" type="text/javascript" charset="utf-8"></script>

script代码:

var counters = {
num1: 0,
fuhao: "",
sum: document.getElementById("sum"),
getnum: function(num) {
this.sum.value += num;
},
getfuhao: function(fuhao) {
this.num1 = this.sum.value;
this.fuhao = fuhao;
this.sum.value = "";

},
getvalue: function() {
this.sum.value=eval(this.num1+this.fuhao+this.sum.value);

}
}

//点击数字,显示数字
var objnum = document.getElementsByName(‘num‘);
for(var i = 0; i < objnum.length; i++) {
objnum.item(i).onclick = function() {
//alert(this.value);
counters.getnum(this.value);
}
}
//点击符号,显示符号
var objfuhao = document.getElementsByName(‘fuhao‘);
for(var j = 0; j < objfuhao.length; j++) {
objfuhao.item(j).onclick = function() {
counters.getfuhao(this.value);
//alert("aa");
}
}
//点击等号,显示结果
var objvalue = document.getElementById(‘dengyu‘);
objvalue.onclick=function(){
counters.getvalue();
//alert(‘aa‘);
}

 

JS之面向对象

标签:pac   type   script   sum   var   htm   i++   cli   length   

原文地址:http://www.cnblogs.com/lfvkit/p/6386550.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!