【问题标题】:jQuery custom background through a cookiejQuery通过cookie自定义背景
【发布时间】:2011-11-20 23:27:52
【问题描述】:

我正在为我的网站制作背景更改脚本。一切正常,除了应该存储所需值的 cookie。我正在使用 jQuery 1.3。 IE 8 说:'对象不支持第 47 行 char 118567432 上的此属性或方法'!?任何帮助将不胜感激。没有 cookie 的工作示例:

    function images(which,image) {
      if (which == 't1')image = images[0];
      else if (which == 't2')image = images[1];//and etc...
    }
    $('html').css("background-image", image);

cookie 示例(不工作):

function images(which,image) {
          if (which == 't1')image = images[0];
            {$.cookie("html_img", "" + image + "", { expires: 7 });
            imgCookie = $.cookie("html_img");}
          else if (which == 't2')image = images[1];
            {$.cookie("html_img", "" + image + "", { expires: 7 });
            imgCookie = $.cookie("html_img");}
          }
        $('html').css("background-image", imgCookie);

【问题讨论】:

  • 请补充一些信息,你有什么错误吗?为 FireFox 安装 FireBug,该插件将显示任何错误。

标签: javascript jquery cookies background


【解决方案1】:

我已将您的代码转换为更高效且语法有效的 JavaScript 代码。

function images(which){
    var image = /^t\d+/i.test(which) ? images[which.substr(1)-1] : null;
    if(image !== null) {
        $.cookie("html_img", image, {expires:7})
    } else {
        image = $.cookie("html_img");
        if(!image) image = images[0]; //If the image doesn't exist, use default=0
    }
    $('html').css("background-image", image);
}

$(document).ready(function(){
    images(); //Load image default from cookie
}

//If you want to change the image+cookie: images("t2");

【讨论】:

  • 谢谢,现在可以了。新问题是,如果我单击指向另一个页面的链接,它会给出默认背景而不是选择的背景。
  • 我改变了答案,因为你的函数逻辑似乎起源于另一个星球。阅读 cmets。
【解决方案2】:

可能是您的“cookie 插件”脚本没有正确导入?您能否提供有关您收到的错误的更多详细信息。使用 Firebug for Firefox 或 Chrome 开发工具来获得更好的错误跟踪。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 2010-10-16
    • 2018-07-13
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多