我几乎在代码的这一步中让所有内容都正常工作,但是,代码可以工作,但由于某种原因仍然显示我似乎无法解决的控制台问题。
index.ejs
<%- include("partials/header") %>
<div class="container my-5">
<div class="row justify-content-center">
<div class="card bg-dark" style="width: 18rem;">
<div class="card-header text-white">
To-Do List
<a href="#collapseToDo" data-toggle="collapse"><i class="fas fa-plus ml-auto"></i></a>
</div>
<ul class="list-group list-group-flush">
<div class="collapse" id="collapseToDo">
<form class="" action="/" method="POST">
<input class="list-group-item bg-light rounded-0" name="todo" type="text" placeholder="Enter To-Do"/>
</form>
</div>
<% todos.forEach(function(todos){ %>
<li class="list-group-item"><%= todos.title %> <form action="/<%= todos._id %>?_method=DELETE" method="POST"><button><i class="far fa-trash-alt"></i></button></form></li>
<% }) %>
</ul>
</div>
</div>
</div>
<%- include("partials/footer") %>
多姆.js
$("ul").on("click", "button", function(event){
$(this).parent().parent().fadeOut(500, function(){
$(this).remove();
});
event.stopPropagation();
});
$("input[type='text']").keypress(function(event){
if(event.which === 13){
var todoText = $(this).val();
$(this).form.submit();
$(".list-group").append("<li class='list-group-item'>" + todoText + "<span><i class='far fa-trash-alt'></i></span></li>");
$(this).val("");
}
});
$(".list-group").on("click", "li", function(){
$(this).toggleClass("completed");
});
我似乎无法$(this).form.submit()
没有任何错误地工作。我收到以下错误:无法读取未定义的属性"提交">
奇怪的是。表单最终确实成功提交,但是由于错误,事件侦听器中的下一行没有通过。有人可以帮助我吗?
用这一行:
$(this).form.submit();
this
是指发生keypress
的input
。input
元素没有form
属性,因此undefined
,undefined
没有submit
方法,因此Cannot read property 'submit' of undefined
错误。
现在,表单最终提交(或至少开始提交(的原因是您的form
中没有submit
按钮,在这种情况下按 ENTER(字符代码 13(会导致submit
。
将行更改为:
$(this).closest("form").submit();
这样就会找到input
最接近的form
祖先元素,然后调用submit
。或者,完全删除该行,让按 ENTER 键启动提交过程,就像它本机所做的那样。
仅供参考:keypress
事件已被弃用。请改用keydown
。