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

时间:2014-03-23 05:24:06

标签: javascript jquery html5 local-storage

单击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);
    }
  }   


});

2 个答案:

答案 0 :(得分:2)

我认为这个解决方案可以为您提供帮助:

$(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. 反序列化数据并存储
  5. 另一种方式:

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

    Idea正在使用命名空间。

答案 1 :(得分:0)

为什么不使用您存储的字符串作为localStorage条目的密钥?