Javascript Closure For Jquery Event Handler
I have a list of objects each of which has a .bullet which is a SPAN. I want to bind a click on the span to a handler than performs a certain action on the span using jQuery. I'm
Solution 1:
Try this:
for (var i = 0 ; i< length ; i++) {
(function(index){
var dataNode = dataNodeList[index];
var handler = function() {
dataNode.bullet.firstChild.nodeValue = "- ";
};
$(dataNode.bullet).on("click",handler);
})(i);
}
The closure defines a new scope. This is necessary because your handler isn't called until after the loop has finished, so i
is not part of the scope at the time it is called, or (in some cases) has the last possible value from the loop.
Post a Comment for "Javascript Closure For Jquery Event Handler"