【问题标题】:How to set a cookie in jquery using toggle()如何使用toggle()在jquery中设置cookie
【发布时间】:2012-03-26 03:48:06
【问题描述】:

当用户点击链接时寻找要设置的 cookie,它将打开 div,然后用户可以刷新页面并看到 div 仍处于打开状态。

=======HTML=======

<a class="show-settings" href="#"></a>

========jQuery=======

$(function () {
//Toggle Settings
var s = $("a.show-settings"); 

//On click to toggle settings
s.click(function () {
    $("#s4-ribbonrow, #s4-titlerow").toggle();
});
//Add/Remove text
s.toggle(function () {
    //$(this).text("Hide Settings");
}, function () {
    //$(this).text("Show Settings");
});

【问题讨论】:

    标签: jquery toggle session-cookies setcookie


    【解决方案1】:

    像这样使用 jquery-cookies 和切换回调功能的东西

    $(document).ready(function() {
     SetView();
    
     $('.show-settings').click(function() {
      $('#s4-ribbonrow, #s4-titlerow').toggle(0, function(){$.cookie('show-settings', $("#s4-ribbonrow:visible")});
     });
    
     function SetView() {
      if ($.cookie('loginScreen') == 'true')
       $('#s4-ribbonrow, #s4-titlerow').show();
     }
    }
    

    【讨论】:

    • 它只是在这里被黑掉了......我没有测试语法是 100%。这就是顶部的评论使用cookie和回调的原因。
    • 有没有办法不用插件?
    • 没有。你必须保持状态。您的要求是“它将打开 div,然后用户可以刷新页面并看到 div 仍然打开”......这需要您将状态保存在 cookie 或会话中,因为网络本质上是无状态的。
    【解决方案2】:

    您需要jQuery cookie 才能使用。

    $(function() {
        var $s = $("a.show-settings");
    
        //On click to toggle settings
        $s.click(function() {
            var text = $(this).text();
            $("#s4-ribbonrow, #s4-titlerow").toggle();
            if(text === 'Show Settings') {
                $s.text('Hide Settings');
                $.cookie('is-hidden', null); // remove cookie
            }else {
                $s.text('Show Settings');
                $.cookie('is-hidden', 'hidden'); // set cookie
                }   
            return false;
        });
        if($.cookie('is-hidden')) { // If cookie exists
            $("#s4-ribbonrow, #s4-titlerow").hide();
            $s.text('Show Settings');
        }
    });
    

    HTML(假设默认显示设置)

    <a class="show-settings" href="#">Hide Settings</a>
    

    【讨论】:

    • 哎呀,我刚刚意识到默认情况下应该隐藏设置。如果需要,我可以修正我的答案。
    • 这是最接近的,但它正在设置 cookie。
    • 还在寻找答案...有没有不使用插件的方法?
    • 不确定你的意思是什么,'它正在设置一个 cookie'?是的,您可以使用 vanilla javascript 来设置 cookie 而不是插件。
    【解决方案3】:

    我之前使用过this jQuery plugin,几乎完全一样的目的。它非常轻量级,而且它的文档很容易理解。

    所以你可以有这样的东西:

    // This is assuming the two elements are hidden by default
    if($.cookie('myCookie') === 'on')
        $("#s4-ribbonrow, #s4-titlerow").show();
    
    s.click(function () {
        $("#s4-ribbonrow, #s4-titlerow").toggle();
    
        // Toggle cookie value
        if($.cookie('myCookie') === 'on')
            $.cookie('myCookie', 'off');
        else
            $.cookie('myCookie', 'on');
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-07
      • 1970-01-01
      • 2020-08-17
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多