一旦我從陣列添加一組動態按鈕,querySelectorAll 似乎沒有取得按鈕清單。 這是我的程式碼:我哪裡出錯了?
const btns = document.getElementById("container"); const textBtn = ["btn 1", "btn 2", "btn 3", "btn 4", "btn 5", "btn 6"] for (i = 0; i < textBtn.length; i++) { btns.insertAdjacentHTML('beforeend', `<button class="allbuttons" value=${textBtn[i]}>${textBtn[i]}</button>`); } const btn = document.querySelectorAll(".allbuttons") for (var i = 0; i < btn.length; i++) { btn[i].addEventListener('click', function(event) { //console.log( btn[i]); console.log(event.target.value); alert(event.target.value) }); }
<div id="container"></div>
P粉2540777472024-03-31 09:53:04
您的問題可能來自於:
<button class="allbuttons" value=${textBtn[i]}>${textBtn[i]}</button>
#您的值不在引號之間<button class="allbuttons" value="${textBtn[i]}">${textBtn[i]}</button>
P粉5750559742024-03-31 00:47:14
有幫助嗎?這是你需要的嗎?
const btns = document.getElementById("container"); const textBtn = ["btn 1", "btn 2", "btn 3", "btn 4", "btn 5", "btn 6"] for (i = 0; i < textBtn.length; i++) { btns.insertAdjacentHTML('beforeend', ``); } const btn = document.querySelectorAll(".allbuttons") for (var i = 0; i < btn.length; i++) { btn[i].addEventListener('click', function(event) { console.log(event.target.value); alert(event.target.value) }); }