When i say…
table[i].add(deleteButton) // this works…
// When i call inside an event listener… it’s says cannot call add of undefined.
imageLogo.addEventListener('click', function (e) {
table[i].add(deleteButton);
} else {
imageLogo.backgroundImage = '/images/markHorizontal.png';
table[i].remove(deleteButton);
}
});
You’ve excluded some important code, but I’ll assume you’re in a
forloop.If so, the issue is that each
clickhandler you’re creating in the loop is referencing the sameivariable. This is because JavaScript (currently) does not have block scope. Only function scope.You need to create a new variable scope for each
ivalue in the loop that you want to persist.By invoking a function in the loop, you’ve created a new variable scope. Because you passed
ito that function, and created your handler in that function, theithat the function references is local to that scope, and will persist.So when the handler is invoked, it is referring to the
ithat was created in the same variable scope where that particular handler was created.There are other variations on the same concept. For example, you could have the function return a function to be used as the handler.