jquery toggle function and set a cookie

一曲冷凌霜 提交于 2019-12-14 03:26:07

问题


I have the following function which toggles mouseenter and mouseleave on click:

var flag = true;
$('.aaa').mouseenter(function () {
    if(flag) {
    $(this).css('background', '#aaaaaa');
    }
    $(this).css('border', 'solid 1px red');
});
$('.aaa').mouseleave(function () {
    if(flag) {
    $(this).css('background','blue');
    }
    $(this).css('border', 'solid transparent 1px');
});
$('#tog').click(function () {
    flag = !flag;
});

http://jsfiddle.net/z8KuE/15/

How can chosen preference be "remembered" and loaded on the next page load?

edit: in case that the solution from bellow doesn't work on the site for some reason, just put it here:

 (function($){
    $(document).ready(function(){
       //Scripts go in here!
    });
 })(jQuery);

回答1:


I would use the jQuery cookie plugin:

var storedFlag = $.cookie('userSelection'); // read cookie
var flag = 1;  //default value
if(storedFlag != undefined){   // some flag was stored
    flag = storedFlag;
}
$('.aaa').mouseenter(function () {
    if(flag > 0) {
        $(this).css('background', '#aaaaaa');
    }
    $(this).css('border', 'solid 1px red');
});
$('.aaa').mouseleave(function () {
    if(flag > 0) {
        $(this).css('background','blue');
    }
    $(this).css('border', 'solid transparent 1px');
});
$('#tog').click(function () {
    flag = 1 - flag;
    $.cookie('userSelection', flag, { expires: 30 }); // store cookie
});

The problem is that the boolean values are stored as strings, and the string 'false' is a true value, thus i resorted to using numbers and >0 comparison.

See updated fiddle



来源:https://stackoverflow.com/questions/19079658/jquery-toggle-function-and-set-a-cookie

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