如何跳过数组中缺少的图像? [复制]
Posted
技术标签:
【中文标题】如何跳过数组中缺少的图像? [复制]【英文标题】: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);
);
【问题讨论】:
【参考方案1】:一种方法是尝试创建图像元素并在加载完成时调用回调
images.each(function( image )
var img = $(new Image()).attr('src', '' + image);
img.on('load', function() console.log("your code after image loaded"); );
【讨论】:
以上是关于如何跳过数组中缺少的图像? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
如何跳过数组的第一个和最后一个元素的循环并将它们设置为常量值?