最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - simple jquery loop through JSON array? - Stack Overflow

programmeradmin2浏览0评论

i have this simple jquery script to loop through JSON array
the script is not working at it all and never give output.
im sure that the JSON array is valid but i don't know why Jquery not parsing it .

$(document).ready(function(){
    var cost = [{"gold":"100","iron":"80","wood":"120","food":"70"},{"gold":"80","iron":"60","wood":"90","food":"35"}];
    var costarr = $.parseJSON(cost);
    $.each(costarr, function(i, item) {
       alert(item.gold);
    }
});

i have this simple jquery script to loop through JSON array
the script is not working at it all and never give output.
im sure that the JSON array is valid but i don't know why Jquery not parsing it .

$(document).ready(function(){
    var cost = [{"gold":"100","iron":"80","wood":"120","food":"70"},{"gold":"80","iron":"60","wood":"90","food":"35"}];
    var costarr = $.parseJSON(cost);
    $.each(costarr, function(i, item) {
       alert(item.gold);
    }
});
Share Improve this question asked Apr 13, 2013 at 23:07 Dr.NeoDr.Neo 1,2804 gold badges17 silver badges29 bronze badges 1
  • 2 if you want to play with javascript at least use a browser console to inspect errors thrown...pretty easy to locate syntax errors you have...and it takes all of 3 seconds to do it! – charlietfl Commented Apr 13, 2013 at 23:14
Add a ment  | 

2 Answers 2

Reset to default 8

You don't need to parse it, it's already an array. And your each lacks a closing )

$.each(cost, function(i, item) {
  alert(item.gold);
}); //<-- lacking ")"

You have a syntax error.

$.each(costarr, function(i, item) {
   alert(item.gold);
}

is missing the ending ');'

which is why nothing is being alerted in your fiddle.

发布评论

评论列表(0)

  1. 暂无评论