简体   繁体   English

jQuery Cookie隐藏/显示div

[英]jQuery Cookie hide/show div

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. 我正在尝试使用jQuery Cookie设置cookie,以便为新访问者显示警报,当您单击“关闭”按钮时,它将设置cookie并阻止警报div显示。 I also want to make the cookie expire after 24 hours. 我还想让cookie在24小时后过期。

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. 我已经玩了一些代码并让它工作,但是,我现在的方式,默认显示警报div,只有在你点击关闭时才隐藏。 This is fine, but when the cookie exists, the alert displays for a split second before being hidden. 这很好,但是当cookie存在时,警报会在隐藏之前显示一瞬间。

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

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默认隐藏警告框,并在没有cookie时使用JavaScript显示它:

CSS: CSS:

.alert-box {
    display: none;
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM