我已经通过 AJAX 调用了一些数据,并且只想使用该数据的一个子集,但不确定如何定位它。 因此,数据描述了顶层的“文件夹”以及每个文件夹内的图像文件名。 基于单击时的链接索引,我想检索同一索引处的文件夹的所有图像名称。
我正在使用 jQuery,因此这是最好的选择。
下面是我的数据结构和我正在尝试的代码:
数据:
[
{"folder":"Folder Name 1",
"images":
[
{"name":"folder_1_image01.jpg"},
{"name":"folder_1_image02.jpg"},
{"name":"folder_1_image03.jpg"}
]
},
{"folder":"Folder Name 2",
"images":
[
{"name":"folder_2_image01.jpg"},
{"name":"folder_2_image02.jpg"},
{"name":"folder_2_image03.jpg"}
]
}
]
代码:
$.ajax({
url: 'my-url-to-json.json',
dataType: 'json',
timeout: 5000,
success: function(data, status){
$('#myLinks a').on('click', function() {
var thisIndex = $(this).index();
$.each(data.images[thisIndex], function(key, value) {
alert(key + ': ' + value);
});
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
最佳答案
尝试
var links = $("#myLinks a");
$.ajax({
url: "url",
dataType: "json",
timeout: 5000,
success: function(data, status){
links.on("click", function(e) {
var thisIndex = $(e.target).index();
var images = data[thisIndex].images;
$.each(images, function(key, value) {
console.log(key + ":" + value.name);
});
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
jsfiddle http://jsfiddle.net/58shtvrc/
关于javascript - 从 JSON 中检索特定索引处的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28512760/