我在页面上显示一个图像,该图像是从我顺序访问的图像数组中调用的。每次重新加载页面时,都会显示数组中的下一个图像。我正在保存到本地存储中,以跟踪上次显示的图像,这样,如果页面关闭,它们下次将从停止的位置开始。这些图像位于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);
}
});
一种方法是尝试创建图像元素,并在加载完成时调用回调
images.each(function( image ) {
var img = $(new Image()).attr('src', '' + image);
img.on('load', function() { console.log("your code after image loaded"); });
}