【问题标题】:can only delete when page reloads只能在页面重新加载时删除
【发布时间】: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


    【解决方案1】:

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

    您有两种处理方法,一种是使用.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"]'))
    

    【讨论】:

    • Live 在 1.7 中被弃用,改用 .on
    • 太棒了!谢谢!但它应该是 live('click', function(){ 在第一个吧?
    猜你喜欢
    • 2011-12-15
    • 2018-03-29
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 2011-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多