使用jQuery cookie显示/隐藏

时间:2011-02-17 23:22:56

标签: jquery cookies

所以我创建了一个简单的提示框,可以在页面加载时淡入,并可以选择关闭该框。如果访问者点击关闭链接,我正试图隐藏该框。我对cookies很新,所以我可能做错了,但这就是我所拥有的:

    $('#close').click(function(e) {
        jQuery.cookie('tip', 'hide', cookieOpts);
        $(this).parent('div.tip').fadeOut(1000);
        e.preventDefault();
    });

    jQuery.cookie('tip', 'show', cookieOpts);

    $('.tip').delay(500).fadeIn(1000);

    var shouldShow = jQuery.cookie('tip') == 'show';
    var cookieOpts = {expires: 7, path: '/'};

    if( shouldShow ) { 
        $('.tip').delay(500).fadeIn(1000); 
    }
    else {            
        $('.tip').css('display', 'none');
    }   

2 个答案:

答案 0 :(得分:1)

我修改了代码:

http://jsbin.com/ujixi4/4/edit

稍微简单一些,希望能达到你想要的效果。

var cookieOpts = {expires: 7, path: '/'};  //this isnt working for some reason
alert('c: '+$.cookie('tip')); //debug code

if( $.cookie('tip') == 'hide'){
  //do nothing
}else{
  $('.tip').delay(500).fadeIn(1000); 
  //$.cookie('tip', 'hide', {expires: 7, path: '/'}); // Add this if you want the cookie to disappear on reload (even if they don't click)
}

$('#close').click(function(e) {
  $.cookie('tip', 'hide', {expires: 7, path: '/'});
  $('.tip').hide();  
});

这是一个使用cookies的类似的awnser: jquery change font-size based on cookie?

http://jsbin.com/ufetu5/2/edit

答案 1 :(得分:0)

您正在传递cookieOpts,但变量在其下方定义。

将它向上移动到首先被引用的位置。