您好,我目前是javascript新手,在理解计算器中for循环的实际工作时遇到了一些问题。我想知道为什么我们要遍历按钮以及javascript在后台如何工作。
这是我苦苦挣扎的代码:
let keypadBtn = document.querySelectorAll(".op-btn");
for(let i = 0; i < keypadBtn.length; i++){
keypadBtn[i].addEventListener("click",function(){
console.log(keypadBtn[i].getAttribute("data-num"));
})
}
<div class="buttons">
<div class="op-btn btn-yellow" data-num = "*">*</div>
<div class="op-btn btn-yellow" data-num = "/">/</div>
<div class="op-btn btn-yellow" data-num = "-">-</div>
<div class="op-btn btn-yellow" data-num = "+">+</div>
<div class="op-btn btn-white" data-num = ".">.</div>
<div class="op-btn btn-white" data-num = "9">9</div>
<div class="op-btn btn-white" data-num = "8">8</div>
<div class="op-btn btn-white" data-num = "7">7</div>
<div class="op-btn btn-white" data-num = "6">6</div>
<div class="op-btn btn-white" data-num = "5">5</div>
<div class="op-btn btn-white" data-num = "4">4</div>
<div class="op-btn btn-white" data-num = "3">3</div>
<div class="op-btn btn-white" data-num = "2">2</div>
<div class="op-btn btn-white" data-num = "1">1</div>
<div class="op-btn btn-white" data-num = "0">0</div>
<div class="op-btn btn-green">=</div>
<div class="op-btn btn-red">C</div>
</div>
实际上我知道代码将如何工作,问题是我想知道 for循环如何通过循环和获取确切的按钮值 没有其他值,因为变量“ i”继续增加值1。 如果“ i”在增加,它如何能够准确地索引我的按钮? 好吧,谢谢
答案 0 :(得分:1)
如果您通常在哪个上遇到迭代问题,我将留给这些教程:Array Iteration,Iteration In General。
现在解释一下代码的作用。
let keypadBtn = document.querySelectorAll('.op-btn') // Grabs all elements containing this the `.op-btn` class
for (let i = 0; i < keypadBtn.length; i++) { // Initializing the for loop
keypadBtn[i].addEventListener('click', () => { // Attach the click event to each of the buttons
// Once click this `console.log` will fire printing
// the element you clicked to browser console
console.log(keypadBtn[i].getAttribute('data-num'))
})
}
答案 1 :(得分:0)
您在上面编写的代码将click事件添加到所有按钮。这里的循环是遍历每个按钮(div)。阅读下面的评论:
let keypadBtn = document.querySelectorAll(".op-btn"); //Select all divs. It picks all the items with class name .opt-btn
for(let i = 0; i < keypadBtn.length; i++){
keypadBtn[i].addEventListener("click",function(){ //attach click event to each button
console.log(keypadBtn[i].getAttribute("data-num")); // you can get the values here and based on it you can calculate the result
})
}