使用jquery cookie插件设置body类

wee*_*zle 0 javascript cookies jquery

我正在尝试用jQuery Cookie插件创建一个"高对比"风格的切换器

我现在已经沉溺了几个小时,在stackoverflow.com上阅读了很多问题,但我没有解决我的问题.

想法是在单击带有"switch"的span元素时在body标签上切换类"highcontrast".在CSS样式表内部我有一套规则,如果body标签有类"highcontrast",我想应用它们.

这是上面场景的jQuery代码:

$("#switch").click(function () {
    $.cookie('bodyclass', 'highcontrast', { expires: 7, path: '/' });
    $('body').toggleClass('highcontrast');
});
Run Code Online (Sandbox Code Playgroud)

如果单击切换元素,则可以切换体类.现在,如果你转到另一个页面,cookie就在那里并设置了值,但是body类"highcontrast"不再存在.

我错过了什么?

der*_*271 5

好的,这已经过验证并正在运行......

HTML:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Style Switcher</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="../../plugins/cookie/jquery.cookie.js"></script>
<script src="switch.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>

<span id="switch">Switch</span>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

jQuery的:

    $(document).ready(function(){
        // Check (onLoad) if the cookie is there and set the class if it is
        if ($.cookie('highcontrast') == "yes") {
            $("body").addClass("highcontrast");
        }

        // When the span is clicked
        $("#switch").click(function () {
            // Check the current cookie value
            // If the cookie is empty or set to no, then add highcontrast
            if ($.cookie('highcontrast') == "undefined" || $.cookie('highcontrast') == "no") {
                // Set cookie value to yes
                $.cookie('highcontrast','yes', {expires: 7, path: '/'});
                // Add the class to the body
                $("body").addClass("highcontrast");
            }
            // If the cookie was already set to yes then remove it
            else {
                $.cookie('highcontrast','no',  {expires: 7, path: '/'});
                $("body").removeClass("highcontrast");
            }
        }); 
    });
Run Code Online (Sandbox Code Playgroud)

CSS:

    body {
        width:100%;
        height:100%;
    }
    body.highcontrast {
        background-color:#000;
        color:#fff;
    }
Run Code Online (Sandbox Code Playgroud)