javascript - 通过 cookie 的 jQuery 自定义背景

标签 javascript jquery cookies background

我正在为我的站点制作背景更改脚本。除了应该存储所需值的 cookie 之外,一切正常。我正在使用 jQuery 1.3。 IE 8 说:“对象不支持第 47 行字符 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);

最佳答案

我已将您的代码转换为更高效、语法更有效的 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");

关于javascript - 通过 cookie 的 jQuery 自定义背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7545691/

相关文章:

javascript - 检测窗口调整大小事件何时完成

javascript - cookie 值未定义(react-cookie 2.0.6)

javascript - 在 Cookies/localStorage 中保存多个 div 位置

javascript - 如何从嵌入页面内部重新加载嵌入页面,而不重新加载 'container' 页面?

javascript - 如何在 Windows 7 上运行脚本编辑器

javascript - Owl Carousel 问题(自动播放+响应式)

jquery - 如何设置 jquery 自动完成中第一个列表项的样式?

java - 在 Vaadin 7 中添加 javascript/Jquery 和客户端代码

javascript - ng-cookie 和主题切换器

javascript - 为什么滚动/跟随菜单在滚动时弹跳?