gpt4 book ai didi

javascript - 没有为寻宝脚本保存 Cookie

转载 作者:行者123 更新时间:2023-11-29 20:14:47 25 4
gpt4 key购买 nike

第一次张贴,长期阅读。

所以我需要创建一个快速简单的寻宝游戏。想法是将一些值存储在 cookie 中,当用户单击具有匹配 id 的元素时,更新以下值。它还不在那里,但是当这个人找到所有 8 个(在这种情况下)时,它会触发一些东西。

现在,我已经基本可以正常工作了,但我遇到了一个大问题。 cookie 不会逐页存储。如果我正在处理单个测试页,那就没问题了——创建 cookie,从中提取值并将其放入检查数组,并且计数器正确递增。此外,当更新 cookie 时,新值将被很好地存储。

但是,当我转到另一个页面并检查 cookie 时,它​​不见了。现在我检查了 cookie 是否真的被放入了,是的,它就在那里。但是有多个 cookie 都具有相同的名称(它们正在更新值 - 但同样只是页面到页面,因此没有累积效应)。

所以,我想我不明白为什么当我调用 cookie 并重置它时,它不会影响单个 cookie 而是创建一个新的 cookie?

哦,我正在使用 jQuery 1.4.2 和 jQuery cookie 插件。

// if not present create default array and store in cookie cookie
if($.cookie('treasure_hunt') == null) {

var treasure = new Array(
"arteContactEn",0,
"arteCorpEn",0,
"arteServicesEn",0,
"arteRoomsEn",0,
"arteDiningEn",0,
"artePackEn",0,
"arteHotelEn",0,
"arteHomeEn", 0
)
$.cookie('treasure_hunt', treasure, { expires: 7 });
}

// capture cookie info
var treasureFound = $.cookie('treasure_hunt');

// create check array and parse values into it
var treasureCheck = new Array();
var treasureCheck = treasureFound.split(',');

// function checks array and tallies total found items
function checkFound() {
var foundItems = 0;

for(var i=0; i<treasureCheck.length; i++) {
var value = treasureCheck[i];
if(value == 1) {
++foundItems;
}
}
// writes found items to span on page
$('.thProgress').text(foundItems);

}

// check number artefacts and write to page
var treasureTotal = treasureCheck.length / 2;
$('.thTotal').text(treasureTotal);

// on click checks element id against array and, if found, marks the following value as 1
$('.artefact-right, .artefact-left').click(function(){
var artefactID = $(this).attr('id');

for(var e=0; e<treasureCheck.length; e++) {
var matchID = treasureCheck[e];
var k = e + 1;

if(matchID == artefactID) {
treasureCheck[k] = 1;

// checks for total found items
checkFound();

// updates cookie with new array
$.cookie('treasure_hunt', treasureCheck, { expires: 7 });
}

}

});

最佳答案

根据README file in github , 如果您不希望它仅适用于创建它的页面,则需要定义 cookie 有效的路径:

Define the path where cookie is valid. By default the path of the cookie is the path of the page where the cookie was created (standard browser behavior). If you want to make it available for instance across the entire page use path: '/'. If you want to delete a cookie with a particular path, you need to include that path in the call.

所以我认为它会是这样的:

$.cookie('treasure_hunt', treasure, { expires: 7, path: '/' });

附言您在 var treasure = new Array() 声明的末尾缺少分号。

关于javascript - 没有为寻宝脚本保存 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7651822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com