我使用 jQuery 显示来自 JSON 文件的图像。但是,当我只想显示每张图片时,这两张图片会出现两次。
JSON:
{
"tiles": [
{
"city": "example",
"img" : "example.jpg"
},
{
"city": "example",
"img" : "example.jpg"
}
]
}
HTML:
<div class="tile-image"></div>
<div class="tile-image"></div>
CSS:
.tile-image img {
width: 432px;
height: 192px;
object-fit: cover;
border-radius: 4px;
}
jQuery:
jQuery(document).ready(function ($) {
var jsonURL = "example.json";
$.getJSON(jsonURL, function (json) {
var imgList = "";
$.each(json.tiles, function () {
imgList += '<div><img src= "' + this.img + '"></div>';
});
$('.tile-image').append(imgList);
});
});
我曾尝试从我的 HTML 中删除两个 div 容器,但是当我这样做时所有图像都消失了。关于为什么它们出现两次而不是一次的任何建议都会很好。
最佳答案
问题是因为您将 imgList
附加到所有 .tile-image
元素。
要解决此问题,您可以改为遍历 .tile-image
并在匹配索引处附加来自响应数据的 img
,如下所示:
// mock AJAX response:
var response = {
"tiles": [{
"city": "example",
"img": "example-1.jpg"
}, {
"city": "example",
"img": "example-2.jpg"
}]
}
jQuery(function($) {
// inside the AJAX callback...
// $.getJSON('example.json', function (response) {
$('.tile-image').each(function(i) {
$(this).append('<div><img src= "' + response.tiles[i].img + '"></div>');
});
// });
});
.tile-image img {
width: 432px;
height: 192px;
object-fit: cover;
border-radius: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tile-image"></div>
<div class="tile-image"></div>
关于javascript - 使用 jQuery 加载图像两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58641750/