jQuery Cookie隐藏/显示div [英] jQuery Cookie hide/show div

查看:93
本文介绍了jQuery Cookie隐藏/显示div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 jQuery Cookie 设置cookie,以便显示警报对于新的访问者,当你点击关闭按钮时,它将设置一个cookie并阻止显示警告div。我也想让这个cookie在24小时后过期。



我已经玩过一些代码并且开始工作了,但是,现在我有了它,警告div默认显示,只有在您点击关闭时才会隐藏。这很好,但是当cookie存在时,该警报会在被隐藏之前显示一秒钟。



如何修改以下代码以便我可以隐藏div默认情况下,如果cookie不存在,它会显示,但如果他们点击关闭按钮,它会生成一个cookie并将警报隐藏24小时?



< $($ .cookie('alert'))$('。alert-box')。hide(); pre> if
else {
$(。close)。click(function(){
$(.alert-box).slideUp(slow,function(){}) ;
$ .cookie('alert',true);
});
}


解决方案

默认情况下使用CSS,并在没有cookie时使用JavaScript显示: > .alert-box {
display:none;

JavaScript:

<$ ($。cookie('alert')){
$(.alert-box).show();如果没有cookie
,则$ p $
$(。close)。click(function(){
$(.alert-box).slideUp(slow);
//将cookie设置为24小时
var date = new Date();
date.setTime(date.getTime()+ 24 * 60 * 60 * 1000);
$ .cookie('alert',true, {expires:date});
});
}


I am trying to set up a cookie using jQuery Cookie so that an alert will be displayed for new visitors and when you click the "close" button it will set a cookie and prevent the alert div from displaying. I also want to make the cookie expire after 24 hours.

I have played around with some code and gotten it to work, however, the way I have it right now, the alert div is shown by default and only hidden once you click close. This is fine, but when the cookie exists, the alert displays for a split second before being hidden.

How would I modify the following code so that I can hide the div by default and if the cookie doesn't exist it will be shown, but then if they hit the close button, it will generate a cookie and hide the alert for 24 hours?

if ($.cookie('alert')) $('.alert-box').hide();
else {
    $(".close").click(function() {
        $( ".alert-box" ).slideUp( "slow", function() { });
        $.cookie('alert', true);
    });
}

解决方案

You can hide the alert-box by default with CSS and use JavaScript to show it when there's no cookie:

CSS:

.alert-box {
    display: none;
}

JavaScript:

// if no cookie
if (!$.cookie('alert')) {
    $( ".alert-box" ).show();
    $(".close").click(function() {
        $( ".alert-box" ).slideUp( "slow" );
        // set the cookie for 24 hours
        var date = new Date();
        date.setTime(date.getTime() + 24 * 60 * 60 * 1000); 
        $.cookie('alert', true, { expires: date });
    });
}

这篇关于jQuery Cookie隐藏/显示div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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