I’ve got an ajax request which returns me JSON data (array of objects).
Iterating this array I generate a list of links. I’d like to set an onClick event and call a function with params from ajax response.
It may sound not clear, so here is an example:
function test(param1) {
// ...
}
$.ajax({
url: 'getSomeData.php',
type: 'post',
data: data,
success: function(result){
var result = JSON.parse(result);
$div = $('<div />');
for (i in result.someObject) {
$div.append('<a href="#" id="linkID' + i + '">ajax link ' + i + '</a>');
$('#linkID' + i).click(function(){
test(result.someObject[i]); // <--- My question is here
return false;
});
}
$(document.body).append($div);
}
});
In my function test I always get the last object of iterated array. I have some idea why this happens, but I don’t know how to fix it.
It’s a problem with the scope of i, if you use a closure to restrict its scope to the click event handler like below it should be fine.
This guarantees that i is at the value it was when the handler was created instead of being the last value it was set at.