jquery切换function并设置cookie
我有以下function,可以在点击时切换mouseenter和mouseleave:
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/
如何选择偏好“记住”并加载到下一页加载?
编辑:如果由于某种原因来自bellow的解决方案在网站上不起作用,请将其放在此处:
(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
比较。
看到更新的小提琴