gpt4 book ai didi

javascript - 本地存储 : condition to prevent storing duplicated values in localStorage

转载 作者:行者123 更新时间:2023-11-27 23:58:29 25 4
gpt4 key购买 nike

单击 li 元素时,我只想将其文本存储为 localStorage 值一次。如果它存在于 localStorage 中,则第二次单击必须无效(只是一个警报)。

为了检查字符串是否存在,我在 for 循环中执行 if,但我做错了。 ( fiddle 线 26)。 我的问题是是否有办法让这个条件发挥作用。

我不能使用颜色作为键,因为我的真实脚本使用大字符串而不是颜色。添加类不是我想解决的方法。

谢谢

http://jsfiddle.net/SXjtd/3/

// Each color must be stored with localStorage once with a click.
// The second click must have no effect, just run an alert.
// LINE 26: the problem is while checking if the value exists
// Colors are used for this example, the real js uses long strings, that's why I can not use the colors as keys.

localStorage.clear();

// define a value that will be used for increment
if (localStorage.getItem('current_id') === null) {
localStorage.setItem('current_id', 0);
}

$(document).on('click', 'li', function() {
var dl = $('dl');
var current_color = $(this).text();

// each click generates a new key
current_key = 'color_id_' + (parseInt(localStorage.getItem('current_id')) + 1);
localStorage.setItem('current_id', (parseInt(localStorage.getItem('current_id')) + 1));

$('<dt>' + current_key + '</dt><dd>' + current_color + '</dd>').appendTo(dl);

// THE PROBLEM IS HERE
// I want to know how to check if a value exists in localStorage
// if this value doesn't exist, it is set in localStorage with a click
for (var i = 0, len = localStorage.length; i < len; i++) {
if (localStorage.getItem('color_id_' + i) == current_color) {
alert('Color exists in localStorage.');
} else {
alert('New Color added to localStorage');
localStorage.setItem(current_id, current_color);
}
}


});

最佳答案

我认为这个解决方案可以帮助到你:

$(document).on('click', 'li', function() {
var color = $(this).text();

if(!localStorage.getItem("colors")){
localStorage.setItem("colors", "[]");
}
var list = JSON.parse(localStorage.getItem("colors"));
var exist = false;
for(var i = 0; i < list.length; i++)
if(list[i] == color) {
exist = true;
break;
}
if(!exist) list.push(color);
else{
alert("EXIST");
}

localStorage.setItem("colors", JSON.stringify(list));
});

工作 demo .

想法是将选定的颜色存储在数组中,然后保存到 localStorage。如果用户点击着色,我们只获取数据序列化,然后检查是否存在。

  1. 获取数据序列化
  2. 检查颜色是否存在
  3. 不存在则保存,否则提示
  4. 反序列化数据并存储

另一种方式:

$(document).on('click', 'li', function() {
var color = $(this).text();
var nSpace = "colors." + color;
if(localStorage.getItem(nSpace))
alert("EXIST");
else
localStorage.setItem(nSpace, true);
});

想法是使用命名空间。

关于javascript - 本地存储 : condition to prevent storing duplicated values in localStorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22587411/

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