从本地存储检查时清除已检查的项目

时间:2016-01-10 00:13:19

标签: javascript jquery html css html5

我在localstorage中有一个数组,我正在打印到浏览器。

我做了一个jsfiddle来展示我的代码结构here.

我正在努力使整个div可点击。换句话说,整个div在点击时会改变颜色,但我隐藏了实际的复选框。

然后我添加了一个按钮,用于清除localstorage中数组中所有已检查的项目。

这样做之后 它几乎可以工作。如果没有剩下的关键字,它只会重新加载数组中的关键字。所以,如果它只显示一个。然后我检查它,它会重新加载。但如果有两个我检查它,它将清除我点击的那个。知道为什么总是保留一个吗?

我正在加载像这样的关键字,

$('#keyWords').prepend('<li class="list-group-item" data-style="button"><input id="'+localArray[i]+'" class="check" name="check" type="checkbox"><label for="'+localArray[i]+'">'+localArray[i]+'</label></li>'); 

然后我想删除像这样的关键字

// Allows user to remove keywords from the locaStorage
$('#clearChecked').click(function() {
  currentArray = [];
  $('.check').each(function() {
    var $curr = $(this);
    if (!$curr.is(':checked')) {
      var value = $curr.parent().text();
      currentArray.push(value);
      localStorage.setItem('keyWords', JSON.stringify(currentArray));
      loadKeyWords();
    } else {
      $curr.parent().remove();
    }
  });

通过删除css复选框,单击li时它是否变为活动状态?这是我能想到为什么这不起作用的唯一原因......在我使整个div可点击之前它正在工作。

以防这是我添加的CSS。

label {
display:block;
line-height:40px;
height:40px;
width: 520px;
border-radius:40px;
-webkit-font-smoothing: antialiased; 
margin-top:10px;
font-family:Arial,Helvetica,sans-serif;
color:gray;
text-align:center;
}

input[type=checkbox] {
display: none;
}

input:checked + label {
color: #F00;
}

input:checked + label:before {
content: "\2713";
}

1 个答案:

答案 0 :(得分:0)

提供的小提琴不起作用,因为你没有为我们提供函数loadKeyWords()。

话虽如此,看起来你正在将整个列表重写为每个循环内的存储。这没有意义,因为你想将所有选项加载到数组中,然后在循环之后设置一次值。

我不确定这是否会帮助您更接近找到问题的真正根源。