单击div即可向Cookie值添加+1 [英] Adding +1 to a cookie value on click of a div

查看:55
本文介绍了单击div即可向Cookie值添加+1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在第一页加载中,设置了一个cookie,其值为0.

On first page load a cookie is set and has a value of 0.

基本上,每次单击 div 时,此人(仅用于客人)都会获得1 EXP,因此,每次 div 是点击+1.该页面不会刷新,因此它需要存储cookie并实时显示,即您已获得50 EXP",然后单击您已获得51 EXP"而无需刷新.但是,如果它们也刷新,那么值也需要保持不变.

Basically each time a div is clicked the person (this is only for guests) earns 1 EXP, so I need to change the cookie value each time the div is clicked by +1. The page won't be refreshed so it needs to store the cookie and show it live, i.e. "You have earned 50 EXP", then click, "You have earned 51 EXP" without a refresh. However the value also needs to stay put if they refresh too.

我在stackoverflow上找到了一些代码,但不确定如何将其关联:

I found some code on stackoverflow but I'm not sure how to relate it:

$(document).ready(function(){

    //set exp cookie
    setCookie("exp", '0');

    //getting the value of exp cookie and assigning it to a variable
    var expCookieCount = getCookie("exp");

    $("#div").one("click",function(){

        expCookieCount++;

        //set the incremented value of expCookieCount variable to exp cookie
        setCookie("exp",expCookieCount);

        // assigning the value of expCookiecount to variable 123
        var 123 = getCookie("exp");

    });

});

推荐答案

  1. 您需要包含有效的cookie脚本,或使用jQuery <一个href ="https://github.com/carhartl/jquery-cookie" rel ="nofollow"> cookie插件.JS和jQuery都没有对cookie的本地支持.

  1. You need to include a valid cookie script or use the jQuery cookie plugin. Neither JS nor jQuery have native support for cookies.

如果不存在,则需要初始化cookie:

You need to initialise the cookie if it does not exist:

FIDDLE

function showExp(exp) {
  $("#someSpan").text("You have "+exp+" point"+(exp==1?"":"s"));
}

$(function(){
  //set exp cookie
  var exp = $.cookie("exp");
  exp = (exp)?parseInt(exp,10):0;
  showExp(exp);

  //getting the value of exp cookie and assigning it to a variable
  $("#div").one("click",function(){ // use .on if you want every click to count
    exp++;
    //set the incremented value of expCookieCount variable to exp cookie
    $.cookie("exp",exp,{ expires: 30, path: '/' }); // expiry date 30 days
    showExp(exp);
  });
});

这篇关于单击div即可向Cookie值添加+1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆