将cookie设置为在每个会话中仅显示div [英] Set cookie to show div only once per session
问题描述
我有一个带有欢迎消息的div,它显示在索引页之前,并且我希望该div在每个会话中仅出现一次。
I have a div with a Welcome message that shows up before the index page and I want that div to appear only once per session.
如何设置一个cookie只能显示一个div?
How would I set a cookie to show a div only once?
我以前从未使用过Cookie,因此,通常我会使用本地存储,但是旧浏览器经常访问此网站,一个问题。
I never used cookies before for something like this, normally I would use Local Storage but this website is visited frequently by older browsers and that's a problem.
推荐答案
您可以查看 document.cookie
等具体示例3:
You may take a look at the documentation of the document.cookie
and more specifically example 3:
if (document.cookie.replace(/(?:(?:^|.*;\s*)someCookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1") !== "true") {
alert("Do something here!");
document.cookie = "someCookieName=true; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/";
}
在此示例中,cookie是使用 expires
标志意味着它将持久存在并在浏览器重启后继续存在。如果您希望每个浏览器会话仅执行一次操作,只需在设置Cookie时删除 expires
标志:
In this example the cookie is created with expires
flag meaning that it will be persistent and survive browser restarts. If you want to perform the action only once per browser session simply remove the expires
flag when setting the cookie:
if (document.cookie.replace(/(?:(?:^|.*;\s*)someCookieName\s*\=\s*([^;]*).*$)|^.*$/, "$1") !== "true") {
alert("Do something here!");
document.cookie = "someCookieName=true; path=/";
}
这篇关于将cookie设置为在每个会话中仅显示div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!