This is a generate table function that generates a table of sites with a corresponding "X" button like so.
I've created an EventHandler for the dynamically created buttons. However, I can only grab the last item in the array. When I print out i, it's always the last index--no matter what button I press.
for (var i=0; i<length; i++) {
console.log(i);
var row = document.createElement("tr");
var site = array[i];
console.log(site);
//create cell & cell text for WEBSITE
var cellWebsite = document.createElement("td");
var website = document.createTextNode(array[i]);
//append cell text to cell, then cell to row (like setting a "stage")
cellWebsite.appendChild(website);
row.appendChild(cellWebsite);
//create a cell & cell text for BUTTON
var cellDelete = document.createElement("td");
var button = document.createElement("BUTTON"); //has its own element
var text = document.createTextNode("x");
button.appendChild(text);
cellDelete.appendChild(button);
row.appendChild(cellDelete);
//event listener for the X button, runs deleteSite function
//with the site text passed through it
button.addEventListener('click', function(event)
{
deleteSite(site);
console.log("deleted : " +site);
});
The array is an array of strings. Not sure how to make sure that the button that is being clicked corresponds to the correct index in the array. How can I change my function?