使用localStorage jQuery删除单个li

时间:2015-07-28 15:29:34

标签: javascript jquery html5 storage local

在使用本地存储时,我是否可以获得有关如何删除单个li的解决方案的帮助?这是待办事项列表类型功能。

我可以选择&删除“this”项,但是,在页面/浏览器上刷新整个ul删除。

我想要做的是只删除所选项目,即使页面/浏览器确实刷新了。

我相信列表[i]可能是我的问题,但我还能从localStorage中选择$(this)?

<h1>simple todo</h1>
<form id="form">
  <input type="text" placeholder="Add New...">
  <button>Add Item</button>
</form>
  <ul id="list"></ul>

<script>
//add
$("button").on("click", function() {
  var $item = $("input").val();
  $("ul").append("<li>" + $item + "</li>");

//set
$('#form')[0].reset();
  var list = $('#list').html();
  localStorage.setItem('list', list);
  return false;
});

//show
if(localStorage.getItem('list')) {
  $('#list').html(localStorage.getItem('list'));
}

//remove
$("ul").on("click", "li", function() {
  $(this).css("color", "gray");
  var i = $(this).val();
  localStorage.removeItem(list[i]);
  localStorage.clear();
});
</script>

1 个答案:

答案 0 :(得分:2)

Change your removing method like this

//remove
$("ul").on("click", "li", function () {
    $(this).css("color", "gray");
    var i = $(this).text();
    var currentList = localStorage.getItem('list');   // get the current list as a string.
    var newList = currentList.replace('<li>' + i + '</li>', '');   // replace the clicked item with a blank string. But if you have multiple tasks with the same name this will cause deleting the first occurrence of it.
    localStorage.setItem('list', newList);  // update the localStorage with the new list
});