How to pass a javascript variable into an Each loop (jQuery) on an JSON object
When an object is clicked on a page I am collecting the data from that object and I need to pass that into a jQuery each loop but substitute my JSON object for the data I have.
Here is my HTML
<a href="#">Large</a>
Here is my JSON Data
var sizeArray = {"Large":{"Red"开发者_如何学JAVA:[78],"Blue":[0],"Green":[0]}
And finally the JS I'm having a problem with
var size = $('a').text();
$.each(sizeArray.size, function(key, val){
if(this == 0){
alert(key);
}});
All I'm getting is an error saying "a is undefined" in jQuery. I know the issue is not with jQuery and the issue is with the par that says "sizeArray.size". If I replace the word size with Large than everything works. I just can't figure out how to pass that in!
Try using:
$.each(sizeArray[size], function(key, val) { ... });
instead.
For more information, check out "Objects as associative arrays"
精彩评论