【问题标题】:Toggle cookies & classes when a button is pressed按下按钮时切换 cookie 和类
【发布时间】:2012-11-30 18:40:29
【问题描述】:

我正在尝试找出一种方法,以便在按下按钮时切换 cookie + 类。

如果:类名称为btn_fixed 的按钮被按下:
- 将 cookie “固定”设置为“真”,
- 将类添加到名为“fixed”的“<header>”中,在加载页面时也会应用“fixed”类,因为 cookie 设置为 true
其他:
- 将cookie“fixed”设置为“false”(默认值,首次进入网站时),
- 从“<header>”中删除“固定”类

这是我到目前为止所得到的,我现在可以看到它与我想要做的相差甚远:

if (jQuery.cookie("fixed") != "true") {  
        jQuery('a.fixed_btn').click(function () {  
            jQuery('header').addClass('fixed');  
            jQuery.cookie("fixed", "true");  
        });  
    }  
    else  
    {  
        jQuery('a.fixed_btn').click(function () {  
            jQuery('header').removeClass('fixed');  
    jQuery.cookie("fixed", "false");
    }  



<a href="#" class="fixed_btn">Fixed/Fluid</a>  
<header>aaa</header>​

http://jsfiddle.net/UWLdq/7/

感谢您的帮助。

【问题讨论】:

  • 请将相关的 html/css/javascript 添加到您的问题中。您的问题应该能够在没有外部资源的情况下独立运行,以便在 jsfiddle 关闭(或在 x 网络中不可用)时,您的问题仍然有效且可以回答。
  • 将 jquery cookie 插件链接添加到 jsfiddle 作为资源,这将有助于解决问题。

标签: javascript jquery cookies setcookie


【解决方案1】:

您只需要最初切换类,然后绑定一个点击事件即可。

jQuery(document).ready(function($) {
    // set class initially based on current cookie value
    $('.cookiefixed').toggleClass('fixed', $.cookie("fixed") == "true");
    // on click, toggle both class and cookie value
    $('a.fixed_btn').click(function() {
        $('.cookiefixed').toggleClass('fixed');
        $.cookie("fixed", $('.cookiefixed').hasClass('fixed'));
    });
});​

我建议不要使用'header' 作为选择器,因为一个页面上可以有多个标题,我怀疑你是否希望他们都获得这个类。

演示:http://jsfiddle.net/UWLdq/6/

【讨论】:

  • 如果你不介意我问,这里发生了什么...!!$.cookie("fixed")
  • 基本上,$.cookie("fixed") 可以返回"true""false"undefined!! 将该值转换为 truefalseundefined!! 只是一个双 !!true === false!!true === true。由于 toggleClass 需要一个布尔值,所以我确保给它一个以避免错误。
  • 所以它基本上只在$.cookie("fixed") === true 时切换课程??
  • 对。 toggleClass 有第二个参数,如果为 true,则始终添加该类,如果为 false,则始终将其删除。第二个参数必须是布尔值,根据api不能是truethy/falsey。
  • 我认为如果 $.cookie("fixed") 的实际值不是真/假,这将不起作用...
【解决方案2】:

这个怎么样:

$(document).on('click','a.fixed_btn',function(){   
    var fixed = jQuery.cookie("fixed");              
    jQuery('header').toggleClass('fixed');
    jQuery.cookie("fixed", fixed === "true" ? "false" : "true");

})

http://jsfiddle.net/UWLdq/5/

【讨论】:

  • 这很好用,但 OP 还需要在页面加载时检查 cookie。干得好!
【解决方案3】:

根据 Bluetoft 的回答,您还需要在页面加载时检查 cookie。

FIDDLE

$(document).on('click','a.fixed_btn',function(){   
    var fixed = jQuery.cookie("fixed");              
    jQuery('header').toggleClass('fixed');
    jQuery.cookie("fixed", fixed === "true" ? "false" : "true");

});

if ($.cookie("fixed") != "true") {
    $('header').addClass('fixed');
}else{
    $('header').removeClass('fixed');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多