繁体   English   中英

localStorage:防止在 localStorage 中存储重复值的条件

[英]localStorage: condition to prevent storing duplicated values in localStorage

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

要检查字符串是否存在,我在 for 循环中执行 if ,但我做错了什么。 (小提琴第 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));     
});

工作演示

这个想法是将选定的颜色存储在数组中,然后保存到 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);
});

想法是使用命名空间。

为什么不直接使用存储的字符串作为 localStorage 条目的键?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM