[英]HTML Button does not call the onclick event
当我运行这个网页时,我无法让按钮运行点击事件。 我正在通过 window.onload function 中的 javascript 创建页面内容,但按钮的事件处理程序不起作用。 我无法让按钮写入控制台。
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) + ' ' + 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
到 select 所有按钮。 然后使用forEach
迭代将eventListener
添加到所有这些按钮。
最后但同样重要的是使用事件委托( 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} ${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>
我重构了您的代码,使其更清晰并符合当前标准。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.