使用 localStorage jQuery 删除单个 li

remove single li using localStorage jQuery

我能得到一些帮助来找到如何在使用本地存储时删除单个 li 的解决方案吗?这是待办事项列表类型的功能。

我能够 select 并删除 "this" 项目,但是,在 page/browser 刷新整个 ul 删除。

我想做的是只删除 selected 项目,即使 page/browser 确实刷新了。

我相信列表[i] 可能是我的问题,但我还能从 localStorage 中 select $(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>

像这样更改您的删除方法

//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
});