variable scope in a getJson grep
Im trying to use a variable within a grep of a getJson request. I want the variable to be defined based on a users' selection (the link they click on) -- but Im not sure how to pass it to the grep because it seems like the varia开发者_开发百科ble has to be defined within the getJson call?
This first example works:
$.getJSON('data/all.json', function(data)
{
location = $.grep(data, function(el, i)
{
var search=el.clicked_field;
return search === "Y"
});
});
This 2nd one doesnt:
var search=el.clicked_field;
$.getJSON('data/all.json', function(data)
{
location = $.grep(data, function(el, i)
{
return search === "Y"
});
});
I think the issue was discussed here in the jQuery forum: http://forum.jquery.com/topic/variable-scoping-and-the-getjson-method
But I havent been able to replicate the proposed solution. Any help would be fantastic...
you're defining el
in the grep's callback in the 2nd one, which is why it's undefined outside that scope.
The only obvious difference in the two pieces of code is the movement of var search=el.clicked_field
out of the context of $.grep
to before the whole code body. At that point, el
doesn't exist, yet. So, unless you have some other piece of code that covers that missing from your post, that's your problem.
EDIT:
Little JavaScript tip. Variables are global within their scope, so take for example the following:
$('#some-element').click(function() {
var someElement = $(this);
$.getJSON('url', function(data, jqXHR){
console.log(someElement); // exists!
});
});
EDIT: (again)
Okay, so you have some fundamental problems in your logic and syntax. It's becoming a bit tedious handling this one aspect at a time in comments, so I'm just going to illustrate:
$('#some-element').click(function() {
var someElement = $(this).attr('href');
// someElement == 'http://google.com'
$.getJSON('data/all.json', function(data) {
location = $.grep(data, function(el, i) {
clicked = someElement.toLowerCase().slice(1);
// clicked == 'ttp://google.com' # Why?
link = 'el' + '.' + clicked;
// link == 'el.ttp://google.com' # Why?
console.log(link); // This bit was for illustrative purposes, you should remove it from your code now.
return link === "Y";
// "el.ttp://google.com" != "Y" # Obviously, and never will
});
});
data
is a list of JavaScript objects. Passing it to $.grep
will cause it to iterate through those objects. Each iteration, the current object will be stored in el
and the index of that object within the data
array will be stored in i
. Take this bit of JSON as an example:
[ { "foo": 1, "bar": 2 } ]
If that was the returned JSON, then el
would have attributes of both foo
and bar
, that you could then use to access the values of each, e.g.:
el.foo == 1 // True
el.bar == 2 // True
Maybe if you actually post your JSON response, I might be able to assist you further. (Update your question, don't post it as a comment)
精彩评论