繁体   English   中英

当按下enter时如何在jquery的待办事项列表中添加新项目

[英]how to add new items in jquery to do list when enter is pressed

我是jquery的新手,需要一些帮助来使待办事项列表在按Enter时添加新项目。 当您单击该按钮时,它的工作正常,但是按Enter键则什么也没有发生。 任何帮助都非常感谢。

<!DOCTYPE html>
<html>
<head>


  </head>
<body>

<form name="toDoList">
  <input type="text" id="listItem" name="ListItem" />
</form>
<ol>
</ol>
<button id="btn2">Add something</button>
<p>something</p>
<p>ldldl</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script>
$(function() {
  $("#btn2").click(function() {
    var toAdd = $("#listItem").val();
    $("ol").append("<li>" + toAdd + "</li>");
  });
  $("#listItem")keydown(function(e) {

  if (e.which === 13) {

      var toAdd = $("#listItem").val();
      $("ol").append("<li>" + toAdd + "</li>");
    }
  });
});

$(document).on('dblclick', 'li', function() {
  $(this).toggleClass('strike').fadeOut('slow');
});



</script> 


</body>
</html>
  • 在嵌套方法.keydown缺少点
  • 您缺少了一个event.preventDefault ,它会阻止表单提交:

 $(function() { $("#btn2").click(function() { var toAdd = $("#listItem").val(); $("ol").append("<li>" + toAdd + "</li>"); }); $("#listItem").keydown(function(e) { if (e.which === 13) { e.preventDefault(); // Don't submit the form $("ol").append("<li>" + this.value + "</li>"); // append this.value this.value = ""; // reset the value field } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="toDoList"> <input type="text" id="listItem" name="ListItem" /> </form> <ol> </ol> <button id="btn2">Add something</button> 

可是

 $(function() { var $input = $("#listItem"), $list = $("ol"); // Don't repeat yourself. Use functions! function addListItem(e) { if(e.type==="keydown" && e.which !== 13) return; e.preventDefault(); // Don't submit form $list.append("<li>" + $input.val() + "</li>"); $input.val(""); // Reset input field } $("#btn2").click(addListItem); $("#listItem").keydown(addListItem); // See the beauty? now you know they both perform the same // addListItem() task and you only have to change the code in one place }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="toDoList"> <input type="text" id="listItem" name="ListItem" /> </form> <ol></ol> <button id="btn2">Add something</button> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM