jquery - 显示来自 json 的图像和标题,但消息说无法读取未定义的属性“图像”
问题描述
<section id="panel">
<div class="container">
</div>
</section>
{
"list": [{
"image": "cat.jpg",
"name": "meow"
}, {
"image": "dog.jpg",
"name": "woof"
}, {
"image": "sheep.jpg",
"name": "baaa"
}, {
"image": "bird.jpg",
"name": "chirp"
}
]
}
$(document).ready(function () {
$.ajax({
url: 'https-url',
type: 'GET',
dataType: 'json',
success: function (data) {
$.each(data.list, function (i, item) {
$("#panel .container .col-sm-6").remove();
var lastItems = data.list.slice(-2);
var content = '<div class="col-sm-6">';
content += '<img class="img-responsive" src="' + lastItems[i].image + '" alt="' + lastItems[i].name + '"/>';
content += '<p>' + lastItems[i].name + '</p>';
content += '</div></div>';
$("#panel .container").append(content);
});
},
error: function (data) {
alert('failed');
}
});
});
Json 会更长,但不管数字多长,我想获取最后两个细节(图像和名称),例如“羊”和“鸟”。item.image
并且item.name
似乎可以工作,但最后 2 个详细信息,尝试使用lastItem[i].image
(名称相同)并收到错误消息。请帮我一些指导。先感谢您。
解决方案
你的代码有2个问题
- 您正在代码中获取属性
cover
,name
而在您的 JSON 中是image
和name
在每个循环中,您将有一个大于您要查找的项目的列表大小的索引 (
lastItems
) 在您的示例变量中,当最后一个索引为 1 时(因为大小为 2) ,您的示例i
变量可以获得值 3 。lastItems
所以你的成功函数应该是这样的:var lastItems = data.list.slice(-2); //You remove the item (this is not necesary to put it into the each loop cause it will return one item (due to you are looking for the element that has that id), if you have more than one then you have to loop through and do something like $(this).remove(); $("#panel .container .col-sm-6").remove(); //You fill the last 2 items $.each(lastItems, function(i, item) { var content = '<div class="col-sm-6">'; content += '<img class="img-responsive" src="' + lastItems[i].cover + '" alt="' + lastItems[i].name + '"/>'; content += '<p>' + lastItems[i].name + '</p>'; content += '</div></div>'; $("#panel .container").append(content); //This will cause an error casue the element with the id #panel will no longer exist (it will be erased with the last remove() call });
推荐阅读
- xpages - 数据视图不显示
- c# - Aspnet cookie 身份验证中间件,在第一个请求中设置身份验证
- selenium - selenium 库在被诗歌添加时无法被 docker 识别
- python - 通过指向两个返回值使函数易于理解
- javascript - 如何防止 Vuejs 中的 dragstart 出现短暂闪烁
- jestjs - NestJS 生命周期事件在 e2e 测试中未按预期执行
- elasticsearch - SpringData(4.x)弹性没有正确序列化实体
- r - 明确 ggplot_build
- unicode - 用 unicode 字符绘制一个水平的 1 行框
- javascript - 如何在此代码段中尝试在控制台中记录日期?