【发布时间】:2014-10-01 21:49:15
【问题描述】:
单击 li 元素时,我只想将其文本存储为 localStorage 值一次。如果它存在于 localStorage 中,则第二次单击必须无效(只是一个警报)。
为了检查字符串是否存在,我在 for 循环中执行了 if,但我做错了。 (小提琴第 26 行)。 我的问题是是否有办法使这种情况发挥作用。
我不能使用颜色作为键,因为我的真实脚本使用大字符串而不是颜色。添加一个类不是我想要解决的方式。
谢谢
// 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);
}
}
});
【问题讨论】:
标签: javascript jquery html local-storage