I am trying to get an object inside the onclick event handler function.
But it is not working the way I expect it to.
For example, if I run this code:
var entries = [{id: 1},{id: 2},{id: 3}];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
document.getElementById(entry.id).onclick = function () {
console.log("this.id: " + this.id);
console.log("entry.id: " + entry.id);
};
}
What I expect is:
this.id: 1
entry.id: 1
this.id: 2
entry.id: 2
this.id: 3
entry.id: 3
But what I get is:
this.id: 1
entry.id: 3
this.id: 2
entry.id: 3
this.id: 3
entry.id: 3
Why is the entry object always the entry with the id 3?
How can I get the correct entry object inside the click event handler?
event.target.idandevent.currentTarget.idattributes. The console is receiving an entry value of 3 because that's the last iteration in the for loop.