我见过许多使用$ .each循环遍历JSON数组的JQuery示例。但是,需要做的是单独抓取项目0 - 3并将它们传递给另一个名为“搜索”的函数。这就是我想出来的。
$.getJSON("http://localhost:61741/binggame/play?cat=Body%20Parts", {
tags: "English",
tagmode: "any",
format: "json"
},
function (data) {
Search(data.items[0], "Box1_Image");
Search(data.items[1], "Box2_Image");
Search(data.items[2], "Box3_Image");
Search(data.items[3], "Box4_Image");
});
我很确定data.items []的语法不正确。
以下是我的JSON示例:
{"nouns":[
{
"ID":26,
"Category":"Body Parts",
"English":"muscle",
"Pinyin":"gei yUk",
"Image1":null,
"Audio1":null
},
{
"ID":27,
"Category":"Body Parts",
"English":"neck",
"Pinyin":"gen",
"Image1":null,
"Audio1":null
},
{
"ID":28,
"Category":"Body Parts",
"English":"nose",
"Pinyin":"bei",
"Image1":null,
"Audio1":null
},
{
"ID":29,
"Category":"Body Parts",
"English":"rib",
"Pinyin":"lat gwt",
"Image1":null,
"Audio1":null
}
]}
对于这个样本,data.items [0]的值应该是“muscle”,data.items [1]应该是“neck”,data.items [2]应该是“nose”和data.items [ 3]应该是“肋骨”。
有人能指出我做错了吗?
答案 0 :(得分:6)
有人能指出我做错了吗?
首先,您的JSON中没有属性名称items
。
如果您想获得"muscle"
:data.nouns[0].English
如果您想获得"neck"
:data.nouns[1].English
等等:
function (data) {
Search(data.nouns[0].English, "Box1_Image");
Search(data.nouns[1].English, "Box2_Image");
Search(data.nouns[2].English, "Box3_Image");
Search(data.nouns[3].English, "Box4_Image");
});
或者,保持DRYer:
function (data) {
var nouns = data.nouns;
function getNoun(i) {
return nouns[i].English;
}
Search(getNoun(0), "Box1_Image");
Search(getNoun(1), "Box2_Image");
Search(getNoun(2), "Box3_Image");
Search(getNoun(3), "Box4_Image");
});
或更好:
function (data) {
var nouns = data.nouns;
for (var i=0; i<4; i++) {
Search(nouns[i].English, 'Box' + (i+1) + '_Image');
}
});
答案 1 :(得分:0)
我假设您正在操作名词属性中的列表,在这种情况下它将是:
for (var i = 0, l = data.nouns.length; i < l; i++) {
Search(data.nouns[i].English, 'Box' + (i + 1) + '_Image');
}