对于一个即将到期的数学元素。
我尝试应用 DRY 概念,但我不知道如何应用。我开始编写一个适用于所有数字的函数,但写到一半时我意识到它根本行不通。匿名函数需要更改我知道,但我现在不能,因为我不知道另一种实现它的方法。
document.querySelector(".button").addEventListener("click", function) {
num = document.getElementById('something');
if (num != null && num === document.getElementById("zero")) {
calculation = calculation.concat("0");
} else if (num != null && num === document.getElementById("one")) {
calculation = calculation.concat("1");
} else if (num != null === && num document.getElementbyId("two")) {
calculation = calculation.concat("2");
} else if (num != nul && num === document.getElementbyId("three")) {
calculation = calculation.concat("3");
} else if (num != nul && num === document.getElementbyId("four")) {
calculation = calculation.concat("4");
} else if (num != nul && num === document.getElementbyId("five")) {
calculation = calculation.concat("5");
} else if (num != nul && num === document.getElementbyId()) {
calculation = calculation.concat("6");
}
}
每个数字都在表格内的按钮内。他们也有 id 来识别他们是哪个号码。我不是在寻找代码,不想窃任何东西。只是寻找关于我可以做些什么的建议。
最佳答案
最简单的方法是编写一个通用函数:
var buttons = document.querySelectorAll("button");
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener(
"click",
function() {
var current_value = this.innerHTML; //typed single number
var display_value = document.getElementById('display').value; //the value on the calculator display
var new_value = display_value + '' + current_value; //+''+ to make it string
document.getElementById('display').value = new_value;
});
}
尝试使用与上述相同的方法通过过滤“+”、“-”等值来添加异常和计算函数。
关于javascript - 不确定如何使这个计算器功能工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43269359/