[英]How to set a cookie to hide a notice bar on second page load?
This is what I wan't: 这就是我要的:
This is my HTML: 这是我的HTML:
<div id="cookie-message">
<span>Cookie notice here <a href="#">Read more</a> <a href="#" id="cookie-message-close">Ok</a></span>
</div>
How can I do this with jQuery? 我该如何使用jQuery?
Thanks! 谢谢!
You can use a API to deal with cookies, makes the things much more easy. 您可以使用API处理Cookie,使事情变得更加容易。
First of all you put display: none;
首先,您要display: none;
in the div cookie-message. 在div cookie消息中。
About the logic of hidden or not the notice, you can put a listener in the first load of the window: 关于隐藏或不通知的逻辑,可以在窗口的第一次加载中放置一个侦听器:
window.addEventListener('load', function(){...});
this way you can get the moment when the window is loaded. 这样,您可以获得当窗口加载时的时刻。 If in this moment there is no cookie for notice read, you show the div ( $('#cookie-message').show()
, and then you set up a cookie. If there is a cookie for that already set, you do nothing. 如果此时没有要通知的cookie,则显示div( $('#cookie-message').show()
,然后设置一个cookie。如果已经设置了cookie,则可以没做什么。
About the OK click, set up a click listener in the link to hide the notice div ( $('#cookie-message').show()
). 关于“确定”单击,在链接中设置一个单击侦听器以隐藏通知div( $('#cookie-message').show()
)。
To help you, I make a simple example example of what I said. 为了帮助您,我举了一个简单的例子说明了我所说的话。
Thanks a lot for your response, Henrique. 非常感谢您的回复,Henrique。 However I couldn't get it to work duo to a "jQuery $.cookie is not a function" error. 但是,我无法使它对“ jQuery $ .cookie不是函数”错误起作用。
I found out that "jQuery Cookie" is deprecated and js-cookie is the new version. 我发现不推荐使用“ jQuery Cookie”,而js-cookie是新版本。 By including that and changing the old cookie functions to the new ones it now works perfectly! 通过包括该功能并将旧的cookie功能更改为新的cookie功能,现在可以完美运行!
This is my final jQuery code, using "js-cookie": 这是我最后的jQuery代码,使用“ js-cookie”:
window.addEventListener('load', function(){
jQuery('#cookie-message-close').click(function(){
jQuery('#cookie-message').hide();
});
if (!Cookies.get("cookie-message-bar"))
{
jQuery('#cookie-message').show();
Cookies.set('cookie-message-bar', true, { expires: 60 });
}
});
Note that I've changed $ to jQuery because of Wordpress' noConflict() mode, since I'm developing in Wordpress. 请注意,由于我在Wordpress中进行开发,由于Wordpress的noConflict()模式,我已将$更改为jQuery。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.