my question may sound like a question about closure but it does have some difference.
var people = [{name: 'john', age: 20},
{name: 'james', age: 25},
{name: 'ryan', age: 19}];
var mainDiv = document.createElement('div', {id: 'mainDiv'});
for (var i = 0; i < people.length; i++) {
var button = document.createElement('button', {}, mainDiv);
var person = people[i];
button.onClick = function (e) {
console.log('printing name');
console.log(person.name);
};
}
This is just an example I made up. Since the person variable is pointing at the last object of the people array, at the end of the for loop, it always prints out the last element when the button is clicked. However what I wanted to achieve is to print out each corresponding person's name when each button is clicked. What should I do to make the inner 'onClick' function to point at the right object?
createElement, is it a custom version? AFAIK it only takes one argument, a tagName. The ids don't show up in the fiddle.var personto the top of the function, as that is where the variable is effectively declared. Even though you're declaringvar personinside the loop, there is only one variablepersonshared by all iterations of the loop. All of your click handlers close over this same variable, which is why they all wind up with the last value. This would be considered a best practice by many seasoned JavaScript developers.