0

I am trying to output the levels read from a json file. Thus, i am having problems adding eventListeners to each Li items.

for(i = 0; i < json.levels.length; i++) {
   $("#id01").append('<li> Level: '+json.levels[i].label+'</li>').addEventListener('click', function(){ console.log(json.levels[i].label);}, false);
}  

I'm getting an undefined error.

I also tried this:

var myLi = document.getElementById('id01').getElementsByTagName('li');

for(i = 0; i < json.levels.length; i++) {
   $("#id01").append('<li> Level: '+json.levels[i].label+'</li>');
   myLi[i].addEventListener('click', function(){ console.log(json.levels[i].label);}, false);
}  

When i click on it i get label undefined.

  • `#id01` is an id. Id's must be unique on the page. How about `"#id"+i` – zipzit Mar 20 '15 at 16:24
  • Wow, I'm way off base with my response. Its deleted... Its not totally clear to me on exactly what you are trying to achieve. I'd recommend building up the html in one loop, then attaching the listeners in a separate loop in a single function. – zipzit Mar 20 '15 at 16:36

0 Answers0