Javascript each loop over JSON only getting first element?

六眼飞鱼酱① 提交于 2019-12-02 02:37:58

each() doesn't work that way. It takes a set of elements on the page, and loops over them, calling a function for each one. In this case, you are looping over $("#tonight-list"), which will only have one item in it (IDs are supposed to uniquely identify one element in a document).

What you seem to want to do is to loop over the data (not the #tonight-list element), and add the data to that element, right? In that case, you want normal JavaScript to do the loop, something like this:

var list = $("#tonight-list");
for (var i=0, place; place=data.Places[i]; ++i) {
    list.append("<li role='option' tabindex='" + i + "'>" + place.name + "</li> ...etc);
}

Note that I have no idea if you are loading trusted data that is meant to contain HTML, untrusted plain text, etc. You may need to encode the data before inserting it or (better) insert it structurally instead of concatenating strings, depending on your use-case.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!