I have a function that creates dynamic buttons and assigns them unique id
and text values. They're created and rendered just fine on the UI, but I'd like to be able to assign them separate onclick
event listeners. The following is the logic in question:
function createLinkButtons(){
for(var i = 0; i < currentOrder.links.length; i++){
currentLink = currentOrder.links[i]
var currentHTML = linksButtonsDiv.innerHTML;
linksButtonsDiv.innerHTML = currentHTML +
`
<button type="button" id="${currentLink.rel}">${currentLink.rel}</button>
`
var button = new Object();
button = document.getElementById(currentLink.rel) //<-- gets overwritten by the next loop iteration
var rel = currentLink.rel;
//onclick function should receive param argument to know how to proceed accordingly
button.onclick = function(rel){
console.log("it workded");
}
}
}
Interestingly, I am able to set the onclick
event to the LAST button that gets created. This is because the last button that gets created "keeps" the onclick
reference. How can I keep all of the previous references to the button alive in memory so that they also react when I click on them?
I've seen other posts in which the dynamically-created buttons are assiged an onclick
event dynamically, but the function is just a signature and does not accept a param argument. I need to include a param argument when invoking the onclick event. Is there any way to do this?