javascript - 使用 jQuery 加载图像两次

标签 javascript jquery html

我使用 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/

相关文章:

javascript - 基础交换回调

html - 考虑到位置必须是绝对的,如何让一个 div 位于另一个 div 之下?

php - 使用循环而不是一条一条地向 MySql 插入数据

javascript - Pentaho 勺子 : JavaScript split is only putting one element in array

javascript - 消除移动分辨率中 div 之间的空白

java - 在上传到服务器之前检查文件内容

javascript - jQuery UI 可拖动超出事件顺序

jquery - 如何设置背景图像离开前景图像的不透明度?

javascript - 发布表单并将结果放入 div 中

javascript - Material Angular 表不包含对象的排序列