javascript - 每次用户进入网站时自动从数组中加载下一张图片
问题描述
因此,每当有人加载我的网站时,此代码都会选择随机图像,我该如何更改代码,以便每次有人加载网站时从头到尾依次选择图像,然后在计数器到达末尾时再次重置为第一张图像?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>
解决方案
使用本地存储来保存您需要的数据[例如访问 = 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);
}
}
推荐阅读
- react-native - 使用 props 控制 modal
- google-cast - 需要开发chromecast内置设备的教程
- c# - 是否可以限制ac#winforms应用程序的内存访问
- webpack - style-loader 如何与 css-loader 一起使用?
- c# - 如何使用正则表达式匹配路由部分中的部分url?WebAPI .NET 核心 2.2
- jquery - 在实现 symfony 表单集合示例时,表单没有嵌入原型,以防一次呈现整个表单
- asynchronous - 重启异步协程,不等待其他协程完成
- jquery - 如何在ajax中选择特定对象?
- jquery - 在 django 中,如何在 ajax 中获取详细的错误信息?
- swift - 我可以在 swift 中几乎等于的基础上比较两个字节值吗