如何使用toggle()在jquery中设置cookie

时间:2012-03-08 16:47:18

标签: jquery toggle session-cookies setcookie

在用户点击链接时查找要设置的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");
});

3 个答案:

答案 0 :(得分:0)

我之前已经非常可靠地使用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');
});

答案 1 :(得分:0)

使用jquery-cookies和toggle的回调功能

这样的东西
$(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();
 }
}

答案 2 :(得分:0)

您需要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>