这完全是一个新手问题,但我的第一个JavaScript任务遇到了严重的问题。我已经决定学习JS,并从TODO列表开始,现在我被困在了一开始。
提交表单时应触发的事件侦听器不起作用。当我将它监听的事件更改为"click“、"focus”或"blur“时,它可以工作,但不能使用submit。有人能给点建议吗?
PS。对event.preventDefault();有什么简单的解释吗?它能做什么,什么时候应该使用它?
万分感谢。
我的HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>TODO</title>
</head>
<body>
<div id="headerDiv">
<h1>My To Do List</h1>
<form>
<input aria-label="Add a new task:" type="text" id="newTaskInput" placeholder="Do the laundry, write a new chapter...">
<input id="submitNewTaskButton" type="submit" value="+">
</form>
</div>
<div id="tasks">
<ul id="tasksList">
<li>Do the laundry</li>
<li>Walk the cat</li>
</ul>
</div>
</body>
<script type="text/javascript" src="script.js"></script>
</html>我的JavaScript:
let newTaskInputForm = document.getElementById('newTaskInput');
let tasksList = document.getElementById("tasksList");
let submitNewTaskButton = document.getElementById("submitNewTaskButton");
function submitNewTask() {
var newTask = newTaskInputForm.value;
var newListItem = document.createElement("li");
var newListTextNode = document.createTextNode(newTask);
newListItem.appendChild(newListTextNode);
tasksList.appendChild(newListItem);
}
newTaskInputForm.addEventListener('submit', function (event) {
event.preventDefault();
submitNewTask(event)
});发布于 2020-03-07 00:21:54
这里做了两个更改,事件侦听器添加到<form>而不是输入提交,还将<input>标记更改为<button>检查this SO question,以了解它们之间的区别。
而对于e.preventDefault(),它基本上用于停止默认的HTML标签行为,例如<a>标签当被点击时,他们会将用户重定向到不同的页面或域,而且表单提交操作通常会将页面重定向到不同的页面,e.preventDefault()将停止这种行为,并让开发人员决定表单提交后应该发生什么,或者<a>锚标签被单击,什么时候应该使用它:这取决于应用程序的设计,所以如果您正在工作的应用程序需要一些HTML标签来执行不同的行为,例如<a>和<form>标签来做Ajax调用。
let newTaskInputForm = document.getElementById('newTaskInput');
let tasksList = document.getElementById("tasksList");
let submitNewTaskButton = document.getElementById("submitNewTaskButton");
function submitNewTask() {
var newTask = newTaskInputForm.value;
var newListItem = document.createElement("li");
var newListTextNode = document.createTextNode(newTask);
newListItem.appendChild(newListTextNode);
tasksList.appendChild(newListItem);
}
document.getElementById('newTaskForm').addEventListener('submit', function (event) {
event.preventDefault();
submitNewTask(event)
});<!DOCTYPE html>
<html lang="en">
<head>
<title>TODO</title>
</head>
<body>
<div id="headerDiv">
<h1>My To Do List</h1>
<form id="newTaskForm">
<input aria-label="Add a new task:" type="text" id="newTaskInput" placeholder="Do the laundry, write a new chapter...">
<button id="submitNewTaskButton" type="submit">+ form</button>
</form>
</div>
<div id="tasks">
<ul id="tasksList">
<li>Do the laundry</li>
<li>Walk the cat</li>
</ul>
</div>
</body>
<script type="text/javascript" src="script.js"></script>
</html>
发布于 2020-03-07 00:12:42
<input>元素不会引发submit事件--它是does that的<form>。
(换句话说,您将侦听器附加到了错误的元素)
https://stackoverflow.com/questions/60567775
复制相似问题