【问题标题】:how to fix toggle first click after reload page如何在重新加载页面后修复切换第一次单击
【发布时间】:2013-06-16 22:25:09
【问题描述】:

我有fiddle

<h2>TITLE INFO</h2>

<div>text 1</div>
<div>text 2</div>
<div>text 3</div>




jQuery('h2').toggle(function () {
    jQuery('body').addClass('order_list');
    $.cookie('info_type', 'order_list', {
        expires: 30
    });
}, function () {
    jQuery('body').removeClass('order_list');
    $.cookie('info_type', null);
});

var order_list_var = $.cookie('info_type');
jQuery('body').addClass(order_list_var);

如果设置了 cookie 并且我重新加载页面,则尝试单击到 h2:没有任何反应 只有当我第二次单击时,cookie 和类才会被删除

【问题讨论】:

    标签: jquery cookies toggle


    【解决方案1】:

    您可以使用click,而不是使用toggle。像这样:

    jQuery('h2').click(function(){
        if (jQuery('body').hasClass('order_list')){
            jQuery('body').removeClass('order_list');
            $.cookie('info_type', null);
        }
        else{
            jQuery('body').addClass('order_list');
            $.cookie('info_type', 'order_list', {
                expires: 30
            });
        }
    });
    

    您遇到的问题是:当您重新加载页面并单击h2 时,无论h2 的当前状态如何,它总是执行toggle 的第一个函数。像这样使用click,您可以完全控制h2的状态

    【讨论】:

    • 非常感谢!现在我明白了))
    猜你喜欢
    • 2018-01-25
    • 2013-11-09
    • 2011-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    相关资源
    最近更新 更多