【发布时间】:2021-06-01 06:07:11
【问题描述】:
我正在尝试使用 html5 localstorage 和一些 JavaScript/jQuery 来创建待办事项列表。我使用 ul 并存储它,它工作正常,我可以将 li 添加到它,当我重新加载页面时它们会保留下来。但是在尝试执行删除功能时,我遇到了一些问题。下面的代码可以在我重新加载页面后删除 li's。但是我不能删除刚刚添加的li。
添加项目时我会这样做:
$(add).click(function(e) {
if (addtext.value != ""){
$(listan).append("<li>" + addtext.value + "</li>"); //listan is my <ul>
localStorage.setItem('todo', listan.innerHTML);
addtext.value = "";
color(); //this adds some color to the li and also adds a delete-button
}
}
color()-函数:
function color(){
lin = document.getElementsByTagName('li');
for (var i = 0; i < lin.length;i++) {
if (!(lin[i].childNodes.length > 1)){
$(lin[i]).append("<input type='button' value='ta bort' class='tabort'></intput>"); //adds a deletebutton to all li's that doesnt have one
}}}
当移除一个项目时,我会这样做:
$('input[type="button"]').click(function() {
if (this.id != 'clear'){
$(this).parent().remove();
color();
localStorage.setItem('todo', listan.innerHTML);
}
});
有什么想法吗?
【问题讨论】:
标签: javascript jquery html local-storage