我正在学习net ninja关于DOM的教程和这个关于表单的视频:https://www.youtube.com/watch?v=n4B7vY9SIds他在整个表单上为提交创建了eventlistener,而不是表单中的按钮,在这种情况下按钮发生了什么,有人能给我解释一下吗?其他人也在下面的评论中问了这个问题,但还没有答案。谢谢。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="styles.css" rel="stylesheet" />
<!--<script src="app.js"></script>-->
<title>JavaScript DOM Tutorials</title>
</head>
<body>
<div id="wrapper">
<header>
<div id="page-banner">
<h1 class="title">Bookorama</h1>
<p>Books for Ninjas</p>
<a href="http://www.thenetninja.co.uk">the net ninja</a>
<form id="search-books">
<input type="text" placeholder="Search books..." />
</form>
</div>
</header>
<div id="book-list">
<h2 class="title">Books to Read</h2>
<ul>
<li>
<span class="name">Name of the Wind</span>
<span class="delete">delete</span>
</li>
<li>
<span class="name">The Wise Man's Fear</span>
<span class="delete">delete</span>
</li>
<li>
<span class="name">Kafka on the Shore</span>
<span class="delete">delete</span>
</li>
<li>
<span class="name">The Master and the Margarita</span>
<span class="delete">delete</span>
</li>
</ul>
</div>
<form id="add-book">
<input type="checkbox" id="hide" />
<label for="hide">Hide all books</label>
<input type="text" placeholder="Add a book..." />
<button>Add</button>
</form>
<div id="tabbed-content">
<ul class="tabs">
<li data-target="#about" class="active">About</li>
<li data-target="#contact">Contact</li>
</ul>
<div class="panel active" id="about">
<p>Content for about tab...</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Vestibulum id nunc porta urna ornare rhoncus. Ut convallis ante
at.</p>
</div>
<div class="panel" id="contact">
<p>Content for contact tab...</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Vestibulum id nunc porta urna ornare rhoncus. Ut convallis ante
at.
</p>
</div>
</div>
</div>
<script src="script.js"></script>
const list = document.querySelector('#book-list ul');
list.addEventListener('click', function(e) {
if(e.target.className == 'delete') {
const li = e.target.parentElement;
li.parentNode.removeChild(li);
}
});
// add book-list
const addForm = document.forms['add-book'];
addForm.addEventListener('submit', function(e) {
e.preventDefault();
const value = addForm.querySelector('input[type="text"]').value;
console.log(value);
})
提交按钮触发表单上的提交事件处理程序。这就是为什么要监听表单上的提交事件,而不是按钮。