JavaScript 使用cookie实现点击次数统计

    科技2024-03-28  68

    通过调用下面两个方法,实现点击次数统计。话不多说上代码

    添加cookie addCookie(cookieName, cookieValue, cookieTimeOut){ if (cookieName != "" && cookieValue != "" && cookieTimeOut != "") { if (isNaN(cookieTimeOut) == false) { let nowDate = new Date(); nowDate.setTime(nowDate.getTime() + 3000*cookieTimeOut) document.cookie = `${cookieName}=${cookieValue};expires=${nowDate.toUTCString()};`//设置cookie的值和过期时间 } else { throw new Error(`过期时间设置失败${cookieTimeOut}。请输入正确值`) } } else { return } }, 获取cookie值 getCookie(cookieName){ let allCookie = document.cookie; let isCookie = allCookie.indexOf(cookieName); if (isCookie != -1) {//如果指定cookie存在,就截取制定cookie的value部分 let start = isCookie + cookieName.length + 1; let end = allCookie.indexOf(';', start); let cookieValue; if (end != -1) { cookieValue = allCookie.substring(start,end); return cookieValue } cookieValue = allCookie.substring(start) return cookieValue } else { this.addCookie("count",0,"6666")//如果未获取到指定cookie就调用addcookie方法添加cookie } }, 这里调用方法--代码较为简洁,大家也可以做二次封装 var target = document.getElementById("target"); var _this = this; //this要做处理,因为this指向变了 if (this.getCookie('count')){ document.getElementById("count").innerHTML = `当前点击${this.getCookie('count')}次!`; } else{ this.addCookie("count","0","6666");//如果未获取到指定cookie就调用addcookie方法添加cookie } target.onclick = function(){ var count = parseInt(_this.getCookie('count'))+1; _this.addCookie("count",count,"6666"); //下面countText 这个要自己写一个标签,用作展示点击次数 document.getElementById("countText").innerHTML = `当前点击${_this.getCookie('count')}次!`; }

    如果有用,劳驾点个赞

    Processed: 0.012, SQL: 8