1. 在前篇基础上进行了以下优化:
对于按键进行分类添加onclick事件:数字类、操作类、特殊处理类,其中数字和操作类都使用了循环,简洁了代码
数字类添加class = 'num':1 、2 、3 、4 、5 、6 、7 、8 、9
操作类添加class = 'op':+ 、 - 、 * 、 / 、 % 、.
特殊处理类使用id去操作如上一篇:ac 、del 、eq 、addordel
2. 优化代码
- 声明
- document.querySelectorAll('')
- 括号中的单引号一定要加
- 返回值是NodeList(),是一个类似数组的集合,不能使用数组方法
var total = '';
// 拿class = 'num'类数组、 class = 'operator'类数组
var numList = document.querySelectorAll('.num');
var opList = document.querySelectorAll('.operator');
- 数字类循环添加onclick事件
// class = 'num'类循环添加onclick
for (var i = 0; i < numList.length; i++) {
numList[i].onclick = function () {
// 将此值拼接在total后面
total = total + this.textContent;
// 将此字符串显示在界面上
framebox.textContent = total;
}
}
- 操作类循环添加onclick事件
- 类似于num类添加操作,但是需要在添加之前判断,字符串最后是什么字符
- 若为它本身就新不添加该加符号操作
- 若为其他operator字符就报错
- 其他情况 就正常添加
// class = 'operator'类循环添加onclick
for (var i = 0; i < opList.length; i++) {
opList[i].onclick = function () {
var temp = framebox.textContent.substring(framebox.textContent.length - 1, framebox.textContent.length);
if (temp == '+' || temp =='-' || temp =='*' || temp =='/' || temp =='%' || temp =='.') {
if (temp == this.textContent) {
//由于没有变化,故可加可不加下面此语句
framebox.textContent = framebox.textContent;
} else {
alert('错误');
}
} else {
if (total == '') {
total = '0';
} else
total = total + this.textContent;
framebox.textContent = total;
}
}
}
- 特殊处理操作用id识别,无改动
// 特殊处理操作
addorsub.onclick = function () {
total = total + '-';
framebox.textContent = total;
}
ac.onclick = function () {
total = '';
framebox.textContent = '0';
}
eq.onclick = function () {
if (total == '') {
framebox.textContent = 0;
} else {
framebox.textContent = eval(total);
total = framebox.textContent;
}
}
del.onclick = function () {
if ('string' == typeof (framebox.textContent)) {
if (framebox.textContent.length > 1) {
total = framebox.textContent.substring(0, framebox.textContent.length - 1);
framebox.textContent = total;
} else {
total = '';
framebox.textContent = '0';
}
}
else {
alert('错误');
}
}
共勉