每个会话设置一次随机背景图像



我对jquery完全陌生。我希望能够随机设置标题背景图像。我不希望每次刷新页面时都更改它。相反,我只想在每节课上设置一次。我假设我需要使用会话cookie,但无法使其工作。

以下是我所拥有的,它在每次刷新的基础上运行良好。我只是想阻止它在每次刷新时发生变化。

$(document).ready(function () {
var randomImages = ['image1', 'image2', 'image3', 'image4', 'image5'];
var rndNum = Math.floor(Math.random() * randomImages.length);
var imageFile = $('#imgpathname').val() + randomImages[rndNum] + ".jpg";
$("div#header").css({ background: "url(" + imageFile + ") no-repeat" });
});

非常感谢您的帮助。

hi为什么不将您的imageID存储在html5存储对象中,如sessionStorage/localStorage,请访问html5存储文档以获取更多详细信息。使用它,您可以临时/永久地在本地存储中间值,然后访问您的值用于存储会话的值

sessionStorage.getItem('label')
sessionStorage.setItem('value', 'label')

或使用永久存储值

localStorage.getItem('label')
localStorage.setItem('value', 'label')

因此,您可以使用html5存储对象在多个页面之间存储(临时)表单数据,您甚至可以在重新加载后保留这些存储对象。。

现在,在您的情况下,您可以将图像ID存储在sessionstorage中,并在刷新页面时使用它,以便在每个会话中加载相同的图像。

jQuery.cookie.js可能会在这里帮助您:

https://github.com/carhartl/jquery-cookie/

从项目页面,创建会话cookie就像一样简单

$.cookie('the_cookie', 'the_value');

然后,您可以在每次加载页面时读取此cookie。

$.cookie('the_cookie'); // => "the_value"

我希望这能有所帮助。如上所述,可以使用HTML5本地存储,但更广泛地支持会话cookie。

最新更新