Linking click event handlers in a loop causing problems in jQuery

I am trying to run the following code:

I pass a parameter to a function, but it always matters the last object that goes through the loop. I read some articles about this in stackoverflow, but I could not figure out how to make it work in my solution.

An object is a JSON object returned from the server. All values ​​are correct.

for(var i = 0;i<parents.length;i++){ var row = $(document.createElement("tr")); var colName = $(document.createElement("td")); var aDisplayCol = $(document.createElement("a")); var parentId = parents[i]['PARENT_ID']; aDisplayCol.attr("href","#").html(parents[i]['NAME']); aDisplayCol.bind('click',function(){ alert(parentId);}); colName.append(aDisplayCol); row.append(colName); $('#pages tbody').append(row); 

}

thanks

+4
source share
3 answers

This is a problem with the area. By the time the function of the event handler was executed, the value of parentId changed and did not reach what you expected.

This can be solved by returning the function of the original event handler to another function, which, in turn, is passed as the parentId value as an argument:

 function getEventHandlerFunction(id){ return function() { alert(id); // variable found in the closure with the expected value }; } aDisplayCol.bind('click', getEventHandlerFunction(parentId)); 
+8
source

There may be a problem using parentId in the callback.

Try alert(parents[i]['PARENT_ID']); .

EDIT: Let's see if we can get around problems with area c . data () .

 aDisplayCol.data("parentId",parents[i]['PARENT_ID']); aDisplayCol.click(function() { alert($(this).data('parentId')); }); 
+2
source

You can avoid clouseres problems with the eventData parameter of the bind function like this

 var message = 'Spoon!'; $('#foo').bind('click', {msg: message}, function(event) { alert(event.data.msg); }); message = 'Not in the face!'; $('#bar').bind('click', {msg: message}, function(event) { alert(event.data.msg); }); 

this is from the jquery bind api documentation http://api.jquery.com/bind/#passing-event-data

+1
source

All Articles