Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

javascript - 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. 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);
    });
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...