【发布时间】: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>
【问题讨论】:
-
您将所有
<li>存储在localStorage 中的一个键下。您还调用localStorage.clear()方法,当您单击任务时,该方法将删除localStorage中的每个项目。这就是导致问题的原因。 -
@Kjell
//show if(localStorage.getItem('list')) { $('#list').html(localStorage.getItem('list')); }在这里他正在加载整个列表并将其显示在#list元素中
标签: javascript jquery html storage local