这是一个生成表函数,它生成一个具有相应的" X"按钮like so.
我为动态创建的按钮创建了一个EventHandler。但是,我只能抓住数组中的最后一项。当我打印出i时,无论我按什么按钮,它总是最后一个索引。
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);
});
数组是一个字符串数组。不确定如何确保正在单击的按钮对应于数组中的正确索引。我怎样才能改变我的功能?