Javascript each loop over JSON only getting first element?

后端 未结 2 1124
醉梦人生
醉梦人生 2021-01-22 15:29

I\'m using Jquery mobile, so ignore some of the following overdone css, its not related to the core issue.

I\'m having a problem looping over the \"Places\" in my JSON p

2条回答
  •  迷失自我
    2021-01-22 16:09

    You are using getJSON and each the wrong way:

    function loadJSON(){
        $.getJSON("http://localhost:8000/api/0.1/tonight-mobile.json&callback=?", callback);
    }
    function callback(data){
        var target = $("#tonight-list");
        $.each(data.Places, function(i) {
            target.append("...");
        });
    }
    

    You have to pass a reference of the callback function do getJSON, not call the function.

    If you do $("#tonight-list").each() then you are iterating over the elements selected by the selector. This function takes only one argument (the callback) anyway. See the documentation.

    You want $.each() which takes an array as first and a callback as second argument.

提交回复
热议问题