javascript - 单击 div 时将 +1 添加到 cookie 值

标签 javascript jquery cookies

在第一页加载时,会设置一个 cookie,其值为 0。

基本上,每次点击 div 时,该人(这仅适用于客人)都会获得 1 EXP,因此我需要在每次 div 被点击时更改 cookie 值点击+1。该页面不会刷新,因此需要存储 cookie 并实时显示,即“您已获得 50 EXP”,然后单击“您已获得 51 EXP”,无需刷新。但是,如果它们也刷新,则该值也需要保持不变。

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

$(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. 您需要包含 a valid cookie script或使用 jQuery cookie plugin 。 JS 和 jQuery 都没有对 cookies 的原生支持。

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

像这样

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);
  });
});

关于javascript - 单击 div 时将 +1 添加到 cookie 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30095738/

相关文章:

javascript - 在部分 View MVC 中使用 jquery/js

javascript - 在父 div 上滚动的同时滚动子 div

jquery - 如何使用 jQuery 删除继承的样式?

http - Golang Cookie Max-Age 与过期

http - 使用 Zend Framework 获取 Cookie 值

javascript - angular.js 和 zurb foundation 显示模态

javascript - 提高 jQGrid 性能

javascript - Streaming-s3 没有正确上传文件到 aws

javascript - jQuery 设置 cookie 到 post 方法

python - virtualenv 之间莫名其妙的 Urllib2 问题。