【问题标题】:Setting up cookie with Javascript使用 Javascript 设置 cookie
【发布时间】:2013-12-05 16:13:44
【问题描述】:

我的 js 应用程序是一个出现日历,用户可以在今天或之前打开一扇“门”,以便 div 背景图像发生变化。

我想设置一个 cookie,这样当他们第二天返回时,div 仍然有背景图像。

我已经设置了 cookie 和开门代码,但我不确定如何将 cookie 集成到开门功能中。任何帮助将不胜感激,非常感谢。

应用链接:http://p3.katecooperuk.com

门打开 - 从数组中选择随机背景图像:

$('.doors').click(function () {

    if (today.getMonth() !== 11) {

        return;
    }

    // Check if the date is tomorrow or later
    if (+($(this).attr('id').split('dec')[1]) > day) {

        // Show image telling user to come back
        $(this).css('background-image', 'url(/images/come_back.png)');

        return;
    }

    // Otherwise it is today or earlier

    // Select Random Image
    var doorImage = getRandomImage(calendarImg);

    // Change background image of door that was clicked
    $(this).css('background-image', doorImage);

});

饼干

//on document ready, checks if the cookie is set, and if so, sets the background with it's value
$(function(){
  if($.cookie('background-image') != null){
     $(this).css('background-image', $.cookie('background-image'));
  }
});

// Set cookie
$(function() {
  $(this).css('background-image', doorImage);
  $.cookie('background-image', doorImage);
 });

【问题讨论】:

    标签: javascript cookies


    【解决方案1】:

    W3Schools 有一个很棒的 cookie 新手教程here

    基本上,您要做的是将 cookie 值设置为它的创建日期以及您想要在用户返回时设置的任何其他参数(例如背景图像的 id)。然后当用户输入你的网站你检查他们是否有cookie。如果有,请检查其日期参数。如果不是今天(这很容易通过JavaScript 进行检查),那么请使用您的额外参数来设置您想要的任何背景。

    确保每当他们更改背景时,您都会将 cookie 数据重置为当前背景。

    希望这会有所帮助!

    *

    根据您的代码,我很难准确理解您想要实现的目标。另外,我正在查看您的网站,但没有看到任何保存的 cookie。尝试从一个简单的示例开始,1 个门和 1 个 cookie。然后做一个简单的检查,看看你的 cookie 是否正常工作,例如,当检测到一个 cookie 时设置一个特定的背景,如果没有,则设置另一个。成功管理 cookie 后,您就可以开始让它变得更复杂,其中包含更多数据。

    【讨论】:

    • Elad - 非常感谢您的建议,我已尝试遵循但仍然无法正常工作,我不确定自己做错了什么。我对 javascript 很陌生——这是我第一次尝试 cookie!我已经更新了上面的代码
    • 我已经编辑了我的原始答案,以便更好地指导您使用 cookie。
    • 如果我的回答让您走上了正确的解决方案,我将不胜感激将其标记为正确答案。如果没有,请让我帮忙!谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 2017-09-05
    • 2019-09-15
    • 2013-07-31
    相关资源
    最近更新 更多