我想弄清楚如何通过 cookie 跟踪用户访问了多少页面。我只想计算他们访问了多少页,并在第 3 页上显示新闻通讯注册表单。这是我当前的脚本,它没有任何计数机制:
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
var hidePopoverCookie = getCookie("hidePopover");
if (hidePopoverCookie == "") { // && pagesVisited > 2
setTimeout(function() {
$("#popOver").show();
}, 5000);
}
$("#popOver button").click(function() {
$("#popOver").hide();
setCookie("hidePopover", true, 365);
})
这就是我要实现的页面计数器:
var pagesVisitedCookie = getCookie("pagesVisited");
if (pagesVisitedCookie === "") {
console.log ("no pages visited");
setCookie("pagesVisted", 1, 365);
} else if (pagesVisitedCookie === 1) {
console.log("2 pages visited");
setCookie("pagesVisted", 2, 365);
} else if (pagesVisitedCookie > 2) {
console.log("More than 2 pages visited");
setCookie("pagesVisted", 3, 365);
}
无论如何它都会返回“没有访问过的页面”,我不确定为什么。我对 cookie 很陌生,我确信有一种更简洁的方法可以做到这一点,我只想完成它(这个项目让我发疯)。
最佳答案
既然我看到你已经在使用 jQuery,我将使用它作为包装函数,它会触发 DOM loaded
事件的实际逻辑,那么你我可以使用 sessionStorage
像这样:
$(function(){ // fires once a page's DOM is ready
var visitsCount = JSON.parse(sessionStorage.getItem('visitsCount'));
if( visitsCount.legnth < 3 && $.inArray( window.location.href, visitsCount ) == -1 ){
visitsCount.push(window.location.href);
sessionStorage.setItem('visitsCount', JSON.stringify(visitsCount));
}
if( visitsCount.legnth >= 3 ) // user has viewed 3 different pages
// do whatever
});
代码将页面的当前 URL 存储在 sessionStorage
中,如果该 URL 不在存储的数组中的话。
关于javascript - 当用户访问 3 个或更多页面时触发函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29373216/