2017-08-04 80 views
0

我一直在做這個簡單的待辦事項列表,現在正處於調試階段。由於我正在實施不同的更改,我觀察到以下內容偶數/不均勻列表項破壞函數

將所有項目都留在列表中: 我添加了1項,沒有問題。 我添加2個項目,沒有任何作品 - 不能標記完整/不完整。 我添加3個項目,沒問題。等等

刷新後的頁面: 我添加1個項目,點擊它,它的工作原理,刪除它,用新項目做一個新列表,不起作用!

我在哪裏開始處理這些錯誤?

https://codepen.io/HelleFl/full/EvNEgd/

$(function() { 
    //$('input[name=checkListItem]').focus(); 
    $(".list-container").hide(); 
    $("hr").hide(); 
    $(".legend").hide(); 

    //* Prevent empty Add from continuing function by Evaluation; It will not accept only spaces; Clear input list once add is clicked; add item & Font Awesome icon to list *// 
    $("#button").click(function() { 
    if ($("input[name=checkListItem]").val().trim() !== "") { 
     var toAdd = $("input[name=checkListItem]").val(); 
     $(".list-container").fadeIn(500); 
     $(".list").append(
     '<div class="item"><i class="fa fa-times" aria-hidden="true"></i><i class="fa fa-pencil" aria-hidden="true"></i>' + 
      toAdd + 
      "</div>" 
    ); 
    } 

    // Focus back on text input once add is clicked 
    $("input[name=checkListItem]").val("").focus(); 

    // click the X icon to remove that item 
    $(document).on("click", ".fa-times", function() { 
     $(this).parent().remove(); 
     if ($(".item").length === 0) { 
     //If container empty, hide from view 
     $(".list-container").hide(); 
     $("hr").fadeOut(500); 
     $(".legend").fadeOut(500); 
     } 
    }); 

    // click on the item to cross it out; click it again to reactivate it 
    $(document).on("click", ".item", function() { 
     if ($(this).css("text-decoration").split(" ")[0] !== "line-through") { 
     $(this).css("text-decoration", "line-through"); 
     $(this).css("color", "gray"); 
     } else { 
     $(this).css("color", ""); 
     $(this).css("text-decoration", ""); 
     } 
    }); 

    //Only show horizontal line if a list is present 
    if ($(".item").length === 0) { 
     $("hr").hide(); 
     $(".legend").hide(); 
    } else { 
     $("hr").fadeIn(500); 
     $(".legend").fadeIn(500); 
    } 
    }); 
}); 
+0

從創建[MVCE](https://stackoverflow.com/help/mcve)開始,特別強調* Minimal *。 –

+0

我沒有看到任何保存任何代碼(用於刷新頁面後)。我錯過了什麼嗎? –

回答

2

您的問題迴避的事實圍繞正在創建每次創建一個新的做動作時新的綁定。當你使用委託綁定時,你不會每次都創建這些綁定。拉出那些在待辦事項創建邏輯之外的內容,並且只在頁面加載時執行一次。

+0

因此,將所有(點擊)委託出來的新項目的創建? – Helle

+0

附加到文檔上的所有事件(event,childSelector,處理程序)都應該被拉出任何重複的邏輯之外,所以它只會發生一次。 – Taplar