jquery切换函数并设置cookie [英] jquery toggle function and set a cookie

查看:131
本文介绍了jquery切换函数并设置cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下函数,它可以切换mouseenter和mouseleave点击:

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);


推荐答案

我会使用 jQuery Cookie插件

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

问题是布尔值存储为字符串,字符串'false'值,因此我诉诸使用数字和> 0 比较。

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.

请参阅更新小提琴

这篇关于jquery切换函数并设置cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆