我有一个像这样的 json 文件:
{
"product": {
images": [
"13953115",
"13953112",
"13953116",
"13953026",
"13953021",
"11519717"
], //etc
}
}
我正在尝试获取仅 第 4 个元素(在上面的示例“13953026”中),然后使用它附加到 div。目前的代码如下所示:
$.getJSON('url-to-product?format=json', function(data){
var images = [];
// how to select the fourth element?//
var image = images[4];
var fourthImage = $('<img src="'+ image +'" width="265" height="340" alt="" />');
$('.con_images').html(fourthImage);
});
我认为 var image = images[4];
会起作用,但显然不是。我在 here 中找到了一些有用的帖子但我不知道如何将其合并到我的代码中。
谁能帮我解决这个问题?谢谢...
最佳答案
我没有发现这样做有任何问题:
$.getJSON('url-to-product?format=json', function(data){
var image = data.product.images[3];
var fourthImage = $('<img src="'+ image +'" width="265" height="340" alt="" />');
$('.con_images').html(fourthImage);
});
另请参阅:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
关于javascript - 仅获取 json 数组中的第 4 个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25465540/