Scoping is the least of your worries. You can always take care of that by
calling some function from your $.getJSON callback, or whatever.

It sounds like you're trying to avoid the multiple $("a.item:contains(key)")
calls, is that right? Those aren't working right as you have it now anyway,
because you're testing for the literal string "key", not the value of the
key. I think you mean $('a.item:contains('+key+')').

Also, do you care if the doStuff() happens before the getJSON request is
made, or can it be done after getJSON responds with the data?

And what about the :contains bit? Can the key actually be any substring of
the anchor text, or would it work to test the entire anchor text string?
That is, given this A tag:

  <a href="...">foo bar</a>

Do you need to be able to match on either 'foo' or 'bar', or do you just
need to be able to match 'foo bar'? If the latter, there is a simple and
fast solution. Let me know and I'll post it.

Finally, I assume you mean a JSON *object*, not an array, correct?

-Mike

> From: yutt
> 
> I need to access a JSON array from outside of the scope of 
> the sub- function. I'm not sure how I can explain it more clearly...
> 
> Basically, I want to do this to save iterating over a 
> specific anchor class more than once. I'll try to provide an example.
> 
> Here is what I currently have to do:
> 
> $("a.item").each(function(index){
>               $(this).doStuff();
> });
> 
> $.getJSON("example.js", function(json){
>               for(key in json){
>                       $("a.item:contains(key)").addClass(json[key]);
>               }
> });
> 
> As you can see, that means I am looping over the same set of 
> anchors multiple times, which seems wildly inefficient. I 
> don't want to go synchronously, because this is just a 
> superficial change and shouldn't delay a user's interaction 
> with the page. Maybe the inefficient second loop is the only 
> way to do it.
> 
> At first glance, it seems moving the doStuff() function 
> inside the getJSON sub-function would be best, but there is 
> no guarantee every anchor will have an associated key, and 
> they all need doStuff().
> 
> Any additional thoughts are appreciated.
> 

Reply via email to