gpt4 book ai didi

javascript - 检查cookie数组元素是否存在

转载 作者:行者123 更新时间:2023-11-30 16:48:34 27 4
gpt4 key购买 nike

如何检查 cookie 中是否已存在数组元素?

这是我的代码:

var cookieList = function (cookieName) {
var cookie = Cookies.get(cookieName);
var items = cookie ? cookie.split(/,/) : new Array();

return {
"add": function (val) {
items.push(val);
Cookies.set(cookieName, items.join(','), { path: '/' });
}
}
}

var list = new cookieList("MyItems");

$('.items').on('click', '.add', function () {
var imageId = $(this).data("id");
list.add(JSON.stringify(imageId));
});

最佳答案

您可以向cookieList 添加一个方法exists,然后使用Array. indexOf()

var cookieList = function (cookieName) {
var cookie = Cookies.get(cookieName);
var items = cookie ? cookie.split(/,/) : new Array();

return {
"add": function (val) {
items.push(val);
Cookies.set(cookieName, items.join(','), {
path: '/'
});
},
exists: function (val) {
return items.indexOf(val) > -1
}
}
}

var list = new cookieList("MyItems");

$('.items').on('click', '.add', function () {
var imageId = $(this).data("id");
list.add(JSON.stringify(imageId));
var exists = list.exists(JSON.stringify(imageId))
});

演示:Fiddle

关于javascript - 检查cookie数组元素是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30884815/

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