0

我对 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" });
});

非常感谢您的帮助。

4

2 回答 2

1

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

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

在项目页面中,创建会话 cookie 非常简单:

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

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

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

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

于 2012-07-24T10:24:13.130 回答
1

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

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

或使用永久存储值

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

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

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

于 2012-07-24T10:21:58.327 回答