Javascript 创建一个id';cookie JS中的s
我想用用户正在访问的帖子id从我的WP页面更新cookie。但我的问题是,每次删除数组中的值时,数组总是只包含一个on id,而下一个id只是过度使用了Javascript 创建一个id';cookie JS中的s,javascript,cookies,Javascript,Cookies,我想用用户正在访问的帖子id从我的WP页面更新cookie。但我的问题是,每次删除数组中的值时,数组总是只包含一个on id,而下一个id只是过度使用了 let post_id = my_script_vars.postID; // this is a variable with some id's let arr = [] // i create an array function setCookie(name,value,days) { var expires = ""; i
let post_id = my_script_vars.postID; // this is a variable with some id's
let arr = [] // i create an array
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
index = arr.indexOf(post_id);
if (index == -1) { // if the id is not in the array the push it
arr.push(post_id);
} else { // if it is in array then keep all of them
arr.splice(index, 1);
}
setCookie("id_film",JSON.stringify(arr),30);
我希望我的数组保留所有id,而不仅仅是一个。按照以下步骤操作:
- 除非需要,否则不要创建
变量arr
- 添加并以JSON形式返回内容
- 在页面加载时,读取cookie,更新数组,然后保存新内容
let post_id = my_script_vars.postID; // this is a variable with some id's
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
}
// Function to read cookie and return as JSON
function getCookie(name) {
let a = `; ${document.cookie}`.match(`;\\s*${name}=([^;]+)`);
return a ? JSON.parse(a[1]) : [];
}
// Be sure to execute after DOM is loaded
window.addEventListener('load', function() {
// Get saved IDs
let arr = getCookie('id_film');
index = arr.indexOf(post_id);
if (index == -1) {
// if the id is not in the array the push it
arr.push(post_id);
}
setCookie("id_film",JSON.stringify(arr),30);
});
获取cookie以将访问过的帖子ID加载到
arr
,然后检查是否需要推送当前ID。它正在工作,但数组始终只有一个ID(当前ID),但我需要所有ID。他的意思是,当初始化“arr”变量时,它应该包含以前的ID。如果您每次初始化“arr”变量并推送新ID,您将只在array.aaa中获得新ID,我如何使用以前的ID初始化arr变量?=)我真的不知道如何将访问过的帖子ID放入ArrayTank u中这么多,最后我明白了这是如何工作的,毕竟并不难,谢谢=)