如何防止用户向JavaScript的待办事项列表中添加4个以上的任务

问题描述 投票:0回答:1

我有一个功能非常简单的待办事项清单。人们可以在输入框中输入新任务,并在添加任务后将其删除,也可以在单击任务时将其划掉以将其选中。我试图防止用户能够向列表中添加4个以上的任务。当用户输入新值并且“要做的事情”列表中已经有4个任务时,应该发出警报,告知他们不能超过4个任务。这是我的代码,由于某种原因它不起作用(它使用户可以根据需要添加任意多个任务:

$("ul").on("click", "li", function() {
    $(this).toggleClass("completed");
});

var task= document.getElementById("task").childElementCount;

// remove to do

$("ul").on("click", "span", function(event) {
  $(this).parent().fadeOut(500, function() {
    $(this).remove();
  });  
    event.stopPropagation();
});



$("input[type='text']").keypress(function(event) {

    if(event.which === 13 && task <= 4) {

        //    grabbing new tasks from user
            var newTask = $(this).val();
            $(this).val("");
            // create a new li and add to ul
            $("ul").append("<li><span><i class='fa fa-trash'></i></span> " + newTask + "</li>")

    } else if (event.which === 13 && task > 4) {
        alert("you are trying to add too many tasks");
    }

}); ``` 
javascript jquery
1个回答
0
投票

好像task未被更新,因为您一次分配了该值,然后始终对照该值进行检查-它不是动态更新的]

您可以在if语句中计算列表中存在多少li,以确保它始终返回正确的金额,或者您可以在将新的task附加到后,更新li的值页面

$("ul").on("click", "li", function() {
  $(this).toggleClass("completed");
});

var task = document.getElementById("task").childElementCount;

// remove to do

$("ul").on("click", "span", function(event) {
  $(this).parent().fadeOut(500, function() {
    $(this).remove();
  });
  event.stopPropagation();
});

$("input[type='text']").keypress(function(event) {

  if (event.which === 13 && $('#task li').length <= 4) {

    //    grabbing new tasks from user
    var newTask = $(this).val();
    $(this).val("");
    // create a new li and add to ul
    $("ul").append("<li><span><i class='fa fa-trash'></i></span> " + newTask + "</li>")

  } else if (event.which === 13 && $('#task li').length > 4) {
    alert("you are trying to add too many tasks");
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.