title: How to add onclick event while creating an element with JavaScript?
body: <p>I have a script where I'm appending elements to a list. I would need that when I click the element a function is called, and for this function the value of a variable when creating the li is needed (it's the <code>li</code> content).</p>
  
  <p>I've checked solutions like adding <code>newLi.onclick = function(){...}</code>.</p>
  
  <p>The problem with this solution is that I'm not getting the right value in the function, I get the value of another element in the list.</p>
  
  <p>Right now this is how I'm creating the elements:</p>
  
  <pre><code>var ULlist = document.getElementById('ULid');
  for(i=0;i&lt;data.length;i++){
     var Value = data[i] //function to get data
     var newLi = document.createElement('li');
     newLi.appendChild(elements.createTextNode(Value));
     newLi.onclick = function(){alert(Value)} //not displaying the right value
     ULlist.appendChild(newLi);
  }
  </code></pre>
  
  <p>So the question is, is there any way to create te onclick event giving to the element the right value of the variable? </p>
  
  <p>Edit: I've added a portion more of code.
  Li's are being created, and information displayed correctly, the only problem is when trying to create the event that it's not giving the right value, that should be the value cointained at the <code>li</code></p>