【问题标题】:How can I skip images that are missing in an array? [duplicate]如何跳过数组中缺少的图像? [复制]
【发布时间】:2021-12-27 08:55:08
【问题描述】:

我正在页面上显示图像,并且图像是从我按顺序访​​问的图像数组中调用的。每次重新加载页面时,都会显示数组中的下一个图像。我正在保存到本地存储以跟踪上次显示的图像,以便如果页面关闭,它们将在下次离开的地方开始。图像位于 CDN 上,它们可能会更改或被删除,但是当阵列尝试访问它们时会失败。有没有办法在找不到数组图像时跳过它们并继续下一个? 感谢您的帮助!

这是我目前所拥有的:

$(function background() {
  var images = [
    "image1.png",
    "image2.png",
    "image3.png",
    "image4.png",
    "image5.png",
    "image_bookend.png"
  ];

  // Check to see if localStorage exists before
  // we do anything

  function hasLocalStorage() {
    try {
      localStorage.setItem("count2", 0);
      if (localStorage.getItem("count2") === "0") {
        return true;
      }
    } catch (e) {
      return false;
    }
    return false;
  }

  // Fetch the count from localStorage. Because it's
  // saved as a string we need to coerce it to a number

  let count = Number(localStorage.getItem("count2"));

  $("#image").css({
    "background-image":
      "url(https://res.cloudinary.com/image/upload/v1636154685/images/" +
      images[count] +
      ")"
  });

  // Increase the count

  count++;

  // If the count is the length of the array (minus one
  // because the array is indexed-based) set the
  // localStorage count to zero, otherwise save the count

  if (count === coupons.length - 1) {
    localStorage.setItem("count2", 0);
  } else {
    localStorage.setItem("count2", count);
  }
});

【问题讨论】:

    标签: javascript arrays image local-storage cdn


    【解决方案1】:

    一种方法是尝试创建图像元素并在加载完成时调用回调

       images.each(function( image ) {
         var img = $(new Image()).attr('src', '' + image);
         img.on('load', function() { console.log("your code after image loaded"); });
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-22
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多