[英]iterating across multiple buttons using key value pairs array to add event listeners with loops
我正在研究一個簡單的計算器項目
我試圖自動將事件監聽器添加到各種數字按鈕(1-9)。
事件偵聽器將偵聽按鈕上的單擊事件,從而導致HTML的顯示部分發生更改(class = .display)
鍵值對是b1-b9,包含各種相應的值。
我想出了下面的FOR EACH循環。 由於某種原因,它會導致所有數字按鈕應用數字9; 我認為這是每個循環的原因。
我不確定如何解決它。 我還提出了一個替代FOR循環,導致另一個問題。 對[Properties [i]]。toString()返回undefined。
有趣的是,如果我將對[Properties [i]]。toString()交換到i,那么就會發生SAME問題
幫助真的很感謝,謝謝你..
const pairs = {
b1: 1,
b2: 2,
b3: 3,
b4: 4,
b5: 5,
b6: 6,
b7: 7,
b8: 8,
b9: 9,
};
var Properties = Object.keys(pairs);
function loadButtons () {
for (var item in pairs) {
//for each key property in pairs
console.log(item);
let targetCell = document.querySelector("." + item.toString())
// querySelector only targets the FIRST element found
// in this case only 1 for that name
console.log(targetCell);
targetCell.addEventListener('click', () => {
// you want it to manipulate the display as and when clicked
var currentDisplay = document.querySelector(".display").innerHTML.toString();
newDisplay = currentDisplay + pairs[item].toString();
document.querySelector(".display").innerHTML = newDisplay;
})
// console.log(pairs[item]);
// // pairs[item] retrieves the value to that "key"
}
};
function alternative() {
var i;
var Properties = Object.keys(pairs);
for (i = 0; i < Properties.length; i++) {
let targetCell = document.querySelector("." + Properties[i].toString())
// querySelector only targets the FIRST element found
// in this case only 1 for that name
console.log(targetCell);
targetCell.addEventListener('click', () => {
// you want it to manipulate the display as and when clicked
var currentDisplay = document.querySelector(".display").innerHTML.toString();
newDisplay = currentDisplay + pairs[Properties[i]].toString();
document.querySelector(".display").innerHTML = newDisplay;
})
};
};
預計應該單擊1將字符串“1”添加到計算器的當前字符串,依此類推。
您應該使用事件委派而不是循環並將事件附加到每個按鈕。 這是一個例子:
var keyboard = document.getElementById('keyboard'); var display = document.getElementById('display'); keyboard.addEventListener('click', function(ev) { var val = ev.target.id; if (ev.target.localName === 'button') { display.innerText += val; } });
.calculator { width: 300px; background: whitesmoke; } #display { height: 50px; background: #d2d2d2; border: 1px solid #9c9c9c; margin: 10px auto 10px; font-size: 20px; line-height: 50px; padding: 0 10px; } #keyboard { display: flex; flex-direction: row; flex-wrap: wrap; justify-content: center; } button { font-size: 20px; padding: 20px; margin: 5px; cursor: pointer; }
<div class="calculator"> <div id="display" contenteditable="true" > </div> <div id="keyboard"> <button id="0">0</button> <button id="1">1</button> <button id="2">2</button> <button id="3">3</button> <button id="4">4</button> <button id="5">5</button> <button id="6">6</button> <button id="7">7</button> <button id="8">8</button> <button id="9">9</button> </div> </div>
我會這樣做,但這不是我猜的唯一一個,可能有更好的方法。
const BUTTONS_NAMESVALUES={ //-- sound awful when a loop can do that! bt0:0,bt1:1,bt2:2,bt3:3,bt4:4,bt5:5,bt6:6,bt7:7,bt8:8,bt9:9 } function checkButtonValue(bt){ if(BUTTONS_NAMESVALUES[bt.id] !=null && BUTTONS_NAMESVALUES[bt.id] !='undefined'){ return bt.innerHTML; }return; } //a button may look like that <button id="bt1">1</button> //-- with listener: document.getElementById('bt1').addEventListener('click', function(e){ let chk=checkButtonValue(this); if(chk!=null && chk!='undefined' && chk!=''){ document.getElementById('calculatorScreen').innerHTML=''+document.getElementById('calculatorScreen').innerHTML+chk; } });
我希望有所幫助。 我只是替換了很容易成為錯誤來源的類名'.display'(因為它是CSS屬性的名稱,在這種情況下,使用id更好地顯示HTML +中的任何內容,因為它是一個獨特的元素,不能是錯誤,類不是)並且不是很准確(因為我寫了一個正確的constante名稱誰有一些意義而不是對誰意味着什么都沒有^^)。
我沒有將代碼自動化為循環,但這是你腳本中的簡單部分。
function onClick(item, pairs) {
return () => {
// you want it to manipulate the display as and when clicked
var currentDisplay = document.querySelector(".display").innerHTML.toString();
var newDisplay = currentDisplay + pairs[item].toString();
document.querySelector(".display").innerHTML = newDisplay;
}
}
var Properties = Object.keys(pairs);
function loadButtons () {
for (var item in pairs) {
//for each key property in pairs
console.log(item);
let targetCell = document.querySelector("." + item.toString())
// querySelector only targets the FIRST element found
// in this case only 1 for that name
console.log(targetCell);
targetCell.addEventListener('click', onClick(item, pairs))
// console.log(pairs[item]);
// // pairs[item] retrieves the value to that "key"
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.