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?