title: How to pass an object to an onclick event
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/341723/event-handlers-inside-a-javascript-loop-need-a-closure">Event handlers inside a Javascript loop - need a closure?</a>  </p>
  </blockquote>
  
  
  
  <p>I am getting some json object through an API call.It is of the folowing format:-</p>
  
  <pre><code>{data:[{id:"1",name:"some1",url:"someurl1"},{id:"2",name:"some2",url:"someurl2"}...]}
  </code></pre>
  
  <p>I get it through a jsonp result and it is parsed as below:-</p>
  
  <pre><code>function(results){
     for(var i=0;i&lt;10;i++){
      item=document.createElement("div");
      item.innerHTML=results.data[i].name;
      item.onclick=function(){
          console.log(results.data[i]);  //---&gt;this is where i am stuck 
        }
      }
   }
  </code></pre>
  
  <p>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</p>
  
  <p>Edit:-
  If I do something like this:-</p>
  
  <pre><code>item.onclick=function(){
    console.log(results.data[1])
  }
  </code></pre>
  
  <p>I get that particular object in the onclick event of all the items , but that is not what i want</p>
  
  <p>Edit:-
  This is how i finally solved it. Thanks to the link pointed to by DCoder.</p>
  
  <pre><code>item.onclick =function(object){
             return function(){
             //do something with the object
             }
  
           }(obj);
  </code></pre>