0

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?

Jules
  • 14,200
  • 13
  • 56
  • 101
DarthCoder
  • 354
  • 1
  • 11
  • The property name is `onclick` not `onClick`. JavaSscript is case sensitive, unlike HTML. Also you have to append the element to the DOM and actually have it load an image. – Felix Kling Jan 29 '13 at 17:42
  • There's no `onClick` property. What does your real code look like? And what does the error actually say? I'm guessing it doesn't use the word "scope". – the system Jan 29 '13 at 17:42
  • yes, i will re-edit the code. but the problem isn't about the onclick working. the web-console says 'data[i] is not defined' i assumed it as the variable scope of the function @the system. – DarthCoder Jan 29 '13 at 17:46
  • @user2022595: Yeah, I know it's not about the onclick. Point is to provide accurate information. – the system Jan 29 '13 at 17:47
  • @thesystem thanks a lot. my first post my bad. will learn quickly ! :) – DarthCoder Jan 29 '13 at 17:49
  • @FelixKling thanks i think the link you referred me to helps :) cheers – DarthCoder Jan 29 '13 at 17:50

1 Answers1

1

Now that you've edited your question I can see the problem XD

The problem is that the onclick function will use the current values of data and (more importantly) i. So essentially it's looking for data[data.length], which by the definition of length doesn't exist.

Instead, you need to "lock" the value of the iterator. Here's how you can do it:

for(i=0; i<data.length; i++) {
  (function(i) {
    // do stuff that relies on i
  })(i);
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592