此代码是一个简单的计算器。输入2个数字,然后按要求的操作获得输出,此代码中没有任何错误。但是,我正在尝试找到将Java代码减少到最短的可能方法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function add(){
var a = parseInt(document.getElementById('no1').value);
var b = parseInt(document.getElementById('no2').value);
document.write(a+b);
}
function sub(){
var a = document.getElementById('no1').value;
var b = document.getElementById('no2').value;
document.write(a-b);
}
function mult(){
var a = document.getElementById('no1').value;
var b = document.getElementById('no2').value;
document.write(a*b);
}
function div(){
var a = document.getElementById('no1').value;
var b = document.getElementById('no2').value;
document.write(a/b);
}
</script>
</head>
<body>
<input type="text" id="no1">
<input type="text" id="no2">
<input type="button" value="ADD" onclick="add()">
<input type="button" value="SUB" onclick="sub()">
<input type="button" value="MULT" onclick="mult()">
<input type="button" value="DIV" onclick="div()">
</body>
</html>
您可以在主体上改用事件委托。单击时,检查单击的元素是否是带有值的输入-如果是,则查找适当的函数以在按值索引的对象上运行(例如ADD
,SUB
):
const fns = {
ADD: (a, b) => a + b,
SUB: (a, b) => a - b,
MULT: (a, b) => a * b,
DIV: (a, b) => a / b,
}
const [no1, no2] = ['no1', 'no2'].map(id => document.getElementById(id));
document.body.addEventListener('click', (e) => {
if (!e.target.matches('input[value]')) {
return;
}
const { value } = e.target;
const fn = fns[value];
console.log(
fn(Number(no1.value), Number(no2.value))
);
});
<input type="text" id="no1">
<input type="text" id="no2">
<input type="button" value="ADD">
<input type="button" value="SUB">
<input type="button" value="MULT">
<input type="button" value="DIV">
它可以做得更短(通过不提前选择元素,或依靠窗口上的id,或不将临时值存储在变量中),但是效率会降低和/或降低可读,所以我不推荐它:
const fns = {
ADD: (a, b) => a + b,
SUB: (a, b) => a - b,
MULT: (a, b) => a * b,
DIV: (a, b) => a / b,
}
document.body.addEventListener('click', ({ target }) => {
if (!target.matches('input[value]')) {
return;
}
console.log(fns[target.value](Number(no1.value), Number(no2.value)));
});
<input type="text" id="no1">
<input type="text" id="no2">
<input type="button" value="ADD">
<input type="button" value="SUB">
<input type="button" value="MULT">
<input type="button" value="DIV">