我通过AJAX调用了一些数据,并希望只使用该数据的一部分,但不确定如何定位它。 因此,数据描述了顶层的“文件夹”和每个文件夹中的图像文件名。 根据点击时的链接索引,我想检索同一索引处文件夹的所有图像名称。
我正在使用jQuery,以便在最佳选择时可用。
以下是我的数据结构和我正在尝试的代码:
DATA:
[
{"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"}
]
}
]
CODE:
$.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.');
}
});
答案 0 :(得分:0)
以下是您的数据的示例点击处理程序。
var data = [
{"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"}
]
}
];
$('.link').on('click', function() {
var idx = $(this).index();
var imgArr = $(data[idx].images);
var images = [];
for (var i = 0; i < imgArr.length; i++) {
images.push(imgArr[i].name);
}
console.log(images);
$('#images').html(images.join('<br />'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<a href="#" class="link">Link 1</a>
<a href="#" class="link">Link 2</a>
</div>
<div id="images"></div>
答案 1 :(得分:0)
尝试
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/