在第一页加载时,会设置一个 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");
});
});
最佳答案
您需要包含 a valid cookie script或使用 jQuery cookie plugin 。 JS 和 jQuery 都没有对 cookies 的原生支持。
如果cookie不存在,则需要初始化:
像这样
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/