问题
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