我一直在研究这个简单的待办事项列表,现在正处于调试阶段。当我实现不同的更改时,我观察到以下情况
保留列表中的所有项目: 我添加 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);
}
});
});
最佳答案
您的问题在于每次创建新的待办事项时都会创建新的绑定(bind)。当您使用委托(delegate)绑定(bind)时,您不必每次都创建它们。将这些内容从待办事项创建逻辑之外拉出来,并且只在页面加载时执行一次。
关于javascript - 偶数/非偶数列表项中断功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45510850/