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?
The standard signature of an event handler delegate defines a method that does not return a value. This method's first parameter is of type Object and refers to the instance that raises the event. Its second parameter is derived from type EventArgs and holds the event data.
Solution. onBlur and onFocus are event/event handler used with text object in JavaScript.
One way to fix this is:
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 (id) {
return function () {
console.log("this.id: " + this.id);
console.log("entry.id: " + id);
};
})(entry.id);
}
You can use a self-executing function (whose purpose is to provide a closure that entry.id will be bound to) to return you a new onclick handler that is bound to the particular id.
If you don't do this, all your onclick handlers get bound to the same entry variable and end up with the last value it received during the for loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With