HTML Button不调用onclick事件



当我运行这个网页时,我无法获得按钮来运行单击事件。我在窗口中通过javascript创建页面的内容。Onload函数,但按钮的事件处理程序不起作用。我无法让按钮写入控制台。

var items = [
"Item 1",
"Item 2",
"item 3",
"item ......etc"
];
window.onload = function() {
// Get container element to append the new element
var container = document.getElementById("myContainer");
// create an HTML element row for each item in the array
for (let i = 0; i < items.length; i++) {
console.log(items[i]);
let strItem = items[i];
// Create a new div element
let newDiv = document.createElement('div');
newDiv.innerHTML = '<div class="row mx-auto py-1"> 
<div class="col-12 col-sm-8 px-5"> 
<label>' + (i + 1) + '&nbsp;&nbsp;' + strItem + '</label> 
</div> 
<div class="col-12 col-sm-4 d-inline-block"> 
<button id="btn' + (i + 1) + '" class="btn btn-primary btn-block btn-sm d-sm-none">Button ' + (i + 1) + '</button> 
<button id="btn' + (i + 1) + '" class="btn btn-primary btn-sm d-none d-sm-inline-block">Button ' + (i + 1) + '</button> 
</div> 
</div>';
// Append the new element
container.appendChild(newDiv);
// Get the button element
let button = document.getElementById('btn' + (i + 1));
// Add an event listener to the button
button.addEventListener('click', function() {
// Do something when the button is clicked
console.log('Button ' + (i + 1) + ' was clicked');
});
}
};
<section id="myContainer"></section>

第一个问题是,您的按钮没有唯一的ID。这就是为什么只有第一个按钮有效。

然后您应该将eventListener移出for循环,并使用querySelectorAll来选择所有按钮。然后使用forEach迭代将eventListener添加到所有这些按钮中。

最后但并非最不重要的是使用事件委托(eventListener函数内部的参数)。这样你就可以读出被点击按钮的id:parameter.target.id

var items = [
"Item 1",
"Item 2",
"item 3",
"item 4"
];
window.addEventListener('DOMContentLoaded', function() {
// Get container element to append the new element
const CONTAINER = document.getElementById('myContainer');
// create an HTML element row for each item in the array
for (let i = 1; i < items.length + 1; i++) {
let strItem = items[i-1];
// Create a new div element
let newDiv = document.createElement('div');
newDiv.innerHTML = `<div class="row mx-auto py-1">
<div class="col-12 col-sm-8 px-5">
<label>${i} &nbsp; &nbsp; ${strItem}</label>
</div>
<div class="col-12 col-sm-4 d-inline-block">
<button id="btn${i}-1" class="btn btn-primary btn-block btn-sm d-sm-none">Button ${i}-1</button>
<button id="btn${i}-2" class="btn btn-primary btn-sm d-none d-sm-inline-block">Button ${i}-2</button>
</div>
</div>`;
// Append the new element
CONTAINER.appendChild(newDiv);
}

//gets all the buttons
const BUTTONS = document.querySelectorAll('button');
//adds an EventListener to all the buttons
BUTTONS.forEach(button =>
button.addEventListener('click', function(element) {
let buttonID = element.target.id;
console.log(`Button ${buttonID} was clicked`);
})
)
});
<section id="myContainer"></section>

我重构了你的代码,使其更清晰,符合当前标准。

最新更新