首页 > 解决方案 > 每次用户进入网站时自动从数组中加载下一张图片

问题描述

因此,每当有人加载我的网站时,此代码都会选择随机图像,我该如何更改代码,以便每次有人加载网站时从头到尾依次选择图像,然后在计数器到达末尾时再次重置为第一张图像?Ps- 代码在托管服务器上运行良好,在这里它给出了一个错误,我不知道为什么。

window.onload = choosePic;

var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");

function choosePic() {
     var randomNum = Math.floor(Math.random() * myPix.length);
     document.getElementById("myPicture").src = myPix[randomNum];
}
<!DOCTYPE html>
<html>
<head>
     <title>Random Image</title>
     <script src="thumb.js"></script>
</head>
<body>
 <img src="images/spacer.gif" id="myPicture" alt="some image">
</body>
</html>

标签: javascriptphphtmlarrays

解决方案


使用本地存储来保存您需要的数据[例如访问 = 3(同一个人第三次访问您的网站)]

你的js代码可以这样实现:

window.onload = choosePic;

var myPix = new Array("https://i.imgur.com/LHtVLbh.jpg", "https://i.imgur.com/2YHazkp.png", "https://i.imgur.com/Uscmgqx.jpg");

function choosePic() {
     if (localStorage.getItem('visited') == null)
     {
         document.getElementById("myPicture").src = myPix[0];
         localStorage.setItem('visited', 1);
     }
     else if (localStorage.getItem('visited') >= myPix.length)
     {
         localStorage.setItem('visited', 0);
         document.getElementById("myPicture").src = myPix[localStorage.getItem('visited')];

     }
     else
     {
         document.getElementById("myPicture").src = myPix[localStorage.getItem('visited')];
         localStorage.setItem('visited', localStorage.getItem('visited') + 1);
     }
}

推荐阅读