[英]To check if user first time visit or not with COOKIES in Servlet
[英]Have div display ONLY on first time visit (cookies?)
我正在嘗試在用戶第一次訪問我的網站時顯示div。 我很確定我是通過使用cookies來做到這一點的,我的經驗有限,並且我很難理解。 我在網上找到的大多數教程都只談到讓cookie讓用戶輸入類似名字的東西,並讓它在以后回憶起來,這根本不是我想要的。 我只是希望cookie檢查用戶之前是否已訪問過我的網站,如果沒有,則顯示通常隱藏的div。
這是我嘗試過但未能開始工作的東西。
HTML:
<head>
<script type="text/javascript" src="annoy.js"></script>
<script type="text/javascript" src="scripts.js"></script>
</head>
...
<body>
<div id="overbox3">
<div id="infobox3">
<p>This is the cookie box</p>
<br />
<p>it should only show once </p>
<br/><br/>
</div><!-- end infobox3 -->
</div> <!-- end overbox3 -->
</body>
CSS(因為這很好用,所以並不相關):
#overbox3 {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
background: rgba(64, 64, 64, 0.5);
z-index: 999999;
display: none;
}
#infobox3 {
margin: auto;
position: absolute;
left: 35%;
top: 20%;
height: 300px;
width: 400px;
background-color: white;
border: 1px solid red;
}
scripts.js的相關內容:
function popbox3() {
$('#overbox3').toggle();
}
而我假設的是問題,annoy.js的內容:
function GetCookie(name) {
var arg=name+"=";
var alen=arg.length;
var clen=document.cookie.length;
var i=0;
while (i<clen) {
var j=i+alen;
if (document.cookie.substring(i,j)==arg)
return "here";
i=document.cookie.indexOf(" ",i)+1;
if (i==0)
break;
}
return null;
}
var visit=GetCookie("COOKIE1");
if (visit==null){
var expire=new Date();
popbox3();
expire=new Date(expire.getTime()+7776000000);
document.cookie="COOKIE1=here; expires="+expire;
}
根據我的理解,cookie應該僅在用戶未訪問時調用函數popbox3(),這將切換隱藏div的顯示。 但截至目前,沒有任何工作。 任何澄清或幫助將不勝感激。 提前致謝。
你的cookie代碼看起來很好。 您需要在文檔就緒處理程序中運行它,以便在切換DIV之前等待文檔加載:
$(function() {
var visit=GetCookie("COOKIE1");
if (visit==null){
popbox3();
}
var expire=new Date();
expire=new Date(expire.getTime()+7776000000);
document.cookie="COOKIE1=here; expires="+expire;
}
我還將cookie設置為無條件,這樣每次訪問該站點都會縮短過期時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.