【问题标题】:Jquery Cookie FunctionjQuery Cookie 函数
【发布时间】:2012-11-08 12:46:13
【问题描述】:

我对此还是很陌生,所以请多多包涵。我有一个在点击事件上添加类的函数,这很好用。但我也希望将单击的功能保存为 cookie,以便当该用户下次访问该站点时,这些类仍然存在/重新应用。我为此使用 jquery.cookie。我的代码如下。

$(".bblue").click(function bblue() {
    $("dl").addClass("bbluebg");
    $("dd .button").addClass("buttonb");
    $('.button img').attr('src',function(i,e){return e.replace("White","DBlue");});
    $.cookie("color", function bblue(){} , { expires: null, path: '/' });
});

当我调用$.cookie('color'); 时返回function bblue(){},但在页面下次加载时它不会运行该函数。

【问题讨论】:

    标签: javascript jquery cookies jquery-cookie


    【解决方案1】:

    我假设您想要存储偏好并据此采取行动。试试这样的:

    // Event-independent color change function
    var bblue = function() {
        $("dl").addClass("bbluebg");
        $("dd .button").addClass("buttonb");
        $('.button img').attr('src', $('.button img').replace("White","DBlue"));
    }
    
    // Click action
    $(".bblue").click(function () {
        // Change the color
        bblue();
        // Store the preference
        $.cookie("color", "blue" , { expires: null, path: '/' });
    });
    
    // On page load
    $(document).load(function() {
        // If they chose blue before, change the color
        if ($.cookie("color") == "blue") bblue();
    });    
    

    【讨论】:

      【解决方案2】:

      该函数没有再次运行,因为页面重新加载时用户没有点击任何内容。您的函数仅在有人单击 .bblue 元素时运行。

      您需要获取 cookie 的值,并在文档就绪时设置适当的类。课程不会坚持,您必须重新申请。你想用...

      $(function() {
          var color = $.cookie("color");
      
          // Set classes according to color here
      });
      

      页面加载后,它将执行并设置所有类。

      【讨论】:

        猜你喜欢
        • 2013-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-23
        • 2011-08-06
        • 1970-01-01
        相关资源
        最近更新 更多