【问题标题】:remove single li using localStorage jQuery使用 localStorage jQuery 删除单个 li
【发布时间】:2015-10-19 06:38:32
【问题描述】:

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

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

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

我相信 list[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>

【问题讨论】:

  • 您将所有&lt;li&gt; 存储在localStorage 中的一个键下。您还调用localStorage.clear() 方法,当您单击任务时,该方法将删除localStorage 中的每个项目。这就是导致问题的原因。
  • @Kjell //show if(localStorage.getItem('list')) { $('#list').html(localStorage.getItem('list')); } 在这里他正在加载整个列表并将其显示在#list 元素中

标签: javascript jquery html storage local


【解决方案1】:

像这样改变你的删除方法

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

【讨论】:

  • 效果很好!我还在学习 JS 和 jQuery,所以我很感激帮助。看到这个就更有意义了,所以谢谢!
  • 也很高兴为您提供帮助! :) 当有多个同名任务时,我将尝试提出解决冲突的解决方案。每当我找到答案时,我都会更新答案! :)
  • 你是善良的!非常感谢先生的帮助。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2011-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多