I have been trying to do this
function test()
{
$.getJSON("http://myurl.com",function (data){
for( i=0; i<data.length; i++){
test = createElement('img');
test.onclick = function (){ myotherfun(data[i]); }
}
}
}
function myotherfun(data)
{
alert(data);
}
An error message states that data isn’t covered by the scope.
Can some one explain why this happens?
Now that you’ve edited your question I can see the problem XD
The problem is that the
onclickfunction will use the current values ofdataand (more importantly)i. So essentially it’s looking fordata[data.length], which by the definition oflengthdoesn’t exist.Instead, you need to “lock” the value of the iterator. Here’s how you can do it: