只能在页面重新加载时删除

can only delete when page reloads

本文关键字:加载 删除 新加载      更新时间:2023-09-26

我正在尝试使用html5 localstorage和一些JavaScript/jQuery做一个待办事项列表。我使用 ul 并存储它,它工作正常,我可以将 li 添加到其中,当我重新加载页面时它们会保留。但是当尝试执行删除功能时,我遇到了一些问题。下面的代码用于在我重新加载页面后删除 li。但是我不能删除刚刚添加的 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);
  
}
});

有什么想法吗?

问题是您刚刚添加的新项目没有附加用于删除的单击处理程序。

您有两种处理方式,一种是使用 .live 而不是 .click (http://api.jquery.com/live/)。另一种是将删除代码包装在一个函数中,并在添加新项后调用该函数。

第一个选项如下所示(未经测试):

$('input[type="button"]').live('click', function() {
    if (this.id != 'clear'){
      $(this).parent().remove();
      color();
      localStorage.setItem('todo', listan.innerHTML);
    }
}); 

第二个选项看起来像

addDeleteHandler = function($item) {
  $item.click(function() {
    if (this.id != 'clear'){
      $(this).parent().remove();
      color();
      localStorage.setItem('todo', listan.innerHTML);
    }
  });
}
// Modify the add handler
$(add).click(function(e) {
  if (addtext.value != ""){
    $newItem = $("<li>" + addtext.value + "</li>")
    $(listan).append($newItem); //listan is my <ul>
    addDeleteHandler($newItem); // Add delete handler
    localStorage.setItem('todo', listan.innerHTML);
    addtext.value = "";
    color(); //this adds some color to the li and also adds a delete-button
  }
}
// Need this to add delete handlers for items that are already in the list when page loads
addDeleteHandler($('input[type="button"]'))