简体   繁体   English

为什么未在Javascript中保存cookie?

[英]Why is not saved cookies in Javascript?

I have a website where I show a temporary message to the user. 我有一个网站,向用户显示临时消息。 This message should behave as follows: 此消息的行为应如下所示:

  • If an user is scrolling, message disappears - slideUp() . 如果用户正在滚动,则消息消失slideUp()
  • If an user clicks on the close button, set css class .closed and stored in the cookie from the buzz shut that after changing to another page again showed up this panel. 如果用户单击关闭按钮,则将css类.closed设置并从蜂鸣声关闭存储在cookie中,在切换到另一页面后,该面板再次显示。

I need to store a cookie when an user clicks on the close button ( .info-close ) panel to update again after this panel does not show. 当用户单击关闭按钮( .info-close )面板以在此面板不显示后再次更新时,我需要存储一个cookie。

There is my problem on jsfiddle . jsfiddle有我的问题。

 $(document).ready(function(){ var $close = $("#info-panel .info-close"); var $info_panel = $("#info-panel"); var $site_main = $(".site-main"); $close.click(function(){ $info_panel.slideUp(); $info_panel.addClass("closed"); // set cookie document.cookie = "1"; // save cookie to "$yes_closed" var $yes_closed = document.cookie; }); $(window).scroll(function() { // if panel has class closed, after click on "X" > dont open // or if in cookie "$yes_closed" is save "1" > dont open if ($info_panel.hasClass("closed")) { $info_panel.hide(); } else { if ($(this).scrollTop() > 0) { $info_panel.slideUp(); } else { $info_panel.slideDown(); } } }); }); 
 #info-panel { padding: 4px 8px; background: yellow; } .info-close { padding: 5px; background: blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <br/><br/><br/> <div id="info-panel"> <div class="info-text">You are reading documentation for version 9.0.1. Documentation for earlier versions is available as pdfs here.</div> <div class="info-close">X</div> </div> <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> <p>"Hello my friend"</p> 

It is because the cookie is not set properly. You need to add a cookie name and assign value to it. On page load do check if the cookie is set. Based on that show the message.

I have your code fixed here in the jsfiddle. Take a look.

http://jsfiddle.net/ssbiswal1987/9bhnyxwn/

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

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