根据freecodecamp
前端轨道构建JS计算器。我的问题是我知道如何使用jQuery实现这一点,但是将其转换为纯javascript时遇到了问题。
Codepen:https://codepen.io/ekilja01/pen/MoXROe
的jQuery :
$("#clear,#clearall").click(function(){
number = "";
totalNumber.text("0");
if ($(this).attr("id") === "clearall") {
newNumber = "";
}
}
我试过这个,但它不起作用
["clear", "clearAll"].forEach.call(function(e){
e.addEventListener("click", function(){
totalNumber.textContent = "0";
});
});
js:
document.addEventListener("DOMContentLoaded", function (event) {
console.log("DOM OK");
// Declare variables for number, new number and operators
var number = "";
var newNumber = "";
var operator = "";
// Declare variable total number to display total on the calculator's display
var totalNumber = document.getElementById("total");
totalNumber.textContent = "0";
// Testing if number displayed is longer than 6 digits and if it is - Err to be displayed
var testNumLength = function(number) {
if (number.length > 6) {
number = "";
totalNumber.textContent = "Err";
}
}
document.getElementById("numbers").addEventListener("click", function(e){
number += e.target.textContent;
totalNumber.textContent = number;
testNumLength(number);
})
var clear = document.getElementById("clear");
var clearAll = document.getElementById("clearall");
})
["clear", "clearAll"].forEach.call(function(e){
e.addEventListener("click", function(){
totalNumber.textContent = "0";
});
});
答案 0 :(得分:1)
此代码对forEah
如何工作
["clear", "clearAll"].forEach.call(function(e){
e.addEventListener("click", function(){
totalNumber.textContent = "0";
});
});
forEach
继承的Array.prototype
方法,因此您不需要使用forEach.call
["clear", "clearAll"]
是一个字符串数组(不是DOM元素)所以你需要构造一个DOM元素数组,或者在forEach
方法中通过id获取这些元素。选择以下选项之一
按ID选择元素并迭代
var clear = document.getElementById("clear");
var clearAll = document.getElementById("clearall");
})
[clear, clearAll].forEach(function(e){
e.addEventListener("click", function(){
totalNumber.textContent = "0";
});
});
或迭代NodeList
来自querySelectorAll
[].forEach.call(document.querySelectorAll('#clear, #clearAll'), function(el) {
...
})
或迭代id并按id
获取元素['clear', 'clearAll'].forEach(function(id) {
document.getElementById(id).addEventListener('click', ...)
})