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

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

  • 添加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')}次!`;
    }

如果有用,劳驾点个赞

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值