我应该怎么做才能将这个数组从随机更改为在页面刷新时按顺序显示

What should I do to change this array from random to appearing in sequence on page refresh?

本文关键字:刷新 显示 顺序 随机 数组 我应该      更新时间:2023-09-26

这是代码。。。我是新手。提前感谢您的建议!

<script type="text/javascript">
$(function () {
var url = "http://localhost:8888/wordpress_hattie/wp-content/uploads/2015/04/",
    imgArray = [url+"paper_shape3.svg",
               url+"mustard_shape2.svg",
               url+"alt_shape.svg"],
    randomNumber = Math.floor((Math.random() * imgArray.length)),
    baseUrl = "url('" + imgArray[randomNumber] + "')";
$(".par_layer").css('background-image', baseUrl);
})();
</script>

您可以将以前使用的映像的索引存储在localStorage中,并在每次运行脚本时递增索引。

var basePath = 'http://localhost:8888/wordpress_hattie/wp-content/uploads/2015/04/';
var fileNames = ['paper_shape3.svg', 'mustard_shape2.svg', 'alt_shape.svg'];
var index = 0;
// Get last index from localStorage if present and increment it by 1.
if (localStorage.getItem('index') !== null) {
  index = Number(localStorage.getItem('index')) + 1;
}
// Reset index to 0 if it exceeds the bounds of fileNames.
if (index >= fileNames.length) {
  index = 0;
}
// Store index in localStorage for later use.
localStorage.setItem('index', index);
$('.par_layer').css('background-image', 'url(' + basePath + fileNames[index] + ')');

我会使用cookie:

var r, m, i;
r = /(?:^|;)'s*i=([^;]+)/;
m = document.cookie.match(r);
i = m ? parseInt(m[1], 10) : 0;
console.log(i); // prints "0" then "1" then "2" then "0"...
document.cookie = "i=" + (++i % 3);

好吧,亲爱的海报,让我们节省你宝贵的时间:

<script type="text/javascript">
$(function () {
var url = "http://localhost:8888/wordpress_hattie/wp-content/uploads/2015/04/",
    imgArray = [url+"paper_shape3.svg", url+"mustard_shape2.svg", url+"alt_shape.svg"],
    r = /(?:^|;)'s*i=([^;]+)/,
    m = document.cookie.match(r),
    i = m ? parseInt(m[1], 10) : 0,
    baseUrl = "url('" + imgArray[i] + "')";
$(".par_layer").css('background-image', baseUrl);
document.cookie = "i=" + (++i % imgArray.length);
})();
</script>

附带说明:如果禁用cookie,将不起作用。

教学说明:localStorage也是如此。