且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Javascript遍历JSON仅获得第一个元素?

更新时间:2023-11-07 14:22:04

each()不能那样工作.它在页面上采用一组元素,并在它们上循环,为每个元素调用一个函数.在这种情况下,您要遍历$("#tonight-list"),它只会包含一个项目(ID应该唯一地标识文档中的一个元素).

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).

您似乎想要做的是遍历 data (不是#tonight-list元素),然后将数据添加到该元素,对吧?在这种情况下,您希望普通的JavaScript进行循环,如下所示:

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);
}

请注意,如果要加载包含HTML,不可信纯文本等内容的受信任数据,我不知道.您可能需要先对数据进行编码,然后再进行插入或(更好地)结构性插入而不是串联字符串,取决于您的用例.

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.