Possible Duplicate:
Event handlers inside a Javascript loop - need a closure?
I am getting some json object through an API call.It is of the folowing format:-
{data:[{id:"1",name:"some1",url:"someurl1"},{id:"2",name:"some2",url:"someurl2"}...]}
I get it through a jsonp result and it is parsed as below:-
function(results){
for(var i=0;i<10;i++){
item=document.createElement("div");
item.innerHTML=results.data[i].name;
item.onclick=function(){
console.log(results.data[i]); //--->this is where i am stuck
}
}
}
How do i pass the particular object from the loop to the onclick event. I mean the first div created should have an onclick event with the data of the first object and the second div should have the data from the second object.. Please ask me if any more clarification is required
Edit:- If I do something like this:-
item.onclick=function(){
console.log(results.data[1])
}
I get that particular object in the onclick event of all the items , but that is not what i want
Edit:- This is how i finally solved it. Thanks to the link pointed to by DCoder.
item.onclick =function(object){
return function(){
//do something with the object
}
}(obj);