Assign event handlers to dynamically created buttons

你说的曾经没有我的故事 提交于 2021-02-20 02:10:00

问题


I am trying to assign a click event handler to dynamically created buttons that once clicked, will return the ID of the clicked button in vanilla Javascript without any frameworks. Yet I can't seem to get the events to handle properly, here's the code

let h = document.getElementsByClassName("buttons");

h.forEach(function() {
	addEventListener("click", function() {
		alert(this.id);
	});
};

回答1:


Try

let h = document.getElementsByClassName("buttons");

[...h].forEach(b => {
  b.addEventListener("click", () => {
    alert(b.id);
  });
});
<button id="btn-id-1" class="buttons">Btn 1</button>
<button id="btn-id-2" class="buttons">Btn 2</button>
<button id="btn-id-3" class="buttons">Btn 3</button>



回答2:


The method document.getElementsByClassName() returns and HTMLCollection wich is an array-like object (but not an array), so you can't use forEach() on it to iterate over his elemtents. Instead, you can use a for loop:

let h = document.getElementsByClassName("buttons");

for (let i = 0; i < h.length; i++)
{
    h[i].addEventListener("click", function()
    {
        alert(this.id);
    });
}
<button id="id1" class="buttons">BUTTON 1</button>
<button id="id2" class="buttons">BUTTON 2</button>

Alternatively, you can spread his element on an array, and then use forEach() on it:

let h = document.getElementsByClassName("buttons");

[...h].forEach(function(btn)
{
    btn.addEventListener("click", function()
    {
        alert(this.id);
    });
});
<button id="id1" class="buttons">BUTTON 1</button>
<button id="id2" class="buttons">BUTTON 2</button>



回答3:


let h = document.getElementsByClassName("buttons");

h.forEach(function(element) {
    element.addEventListener("click", function() {
        alert("Hello");
    });
};


来源:https://stackoverflow.com/questions/54987490/assign-event-handlers-to-dynamically-created-buttons

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!