How to set a cookie in jquery using toggle()

好久不见. 提交于 2019-12-12 11:42:22

问题


Looking for a cookie to be set when the user clicks on the link it'll open the div then the user can refresh the page and see the div is still open.

=======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");
});

回答1:


Something like this using jquery-cookies and the callback functionality from 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:


I've used this jQuery plugin before quite reliably for almost the exact same purpose. It's very light-weight and the documentation for it is pretty easy to follow.

So you could have something like this:

// 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');
});



回答3:


You'll need jQuery cookie for this to work.

$(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 (assumes settings are shown by default)

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


来源:https://stackoverflow.com/questions/9621427/how-to-set-a-cookie-in-jquery-using-toggle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!