为什么在待办列表中添加项目后页面会刷新?
Why is the page refreshing after I add an item to the To Do list?
我刚刚学会了如何创建和追加项目。我想练习使用按钮提交要附加的文本。它有效,但是,该页面似乎随后立即刷新并从列表中删除了文本。我做错了什么?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To Do List</title>
<link rel="stylesheet" href="ToDo.css">
</head>
<body>
<h1>To Do:</h1>
<ul>
<li class="todo">Create another todo.</li>
</ul>
<form>
<input type="text" placeholder="Add another item!">
<button onclick="output()">Add</button>
</form>
<script src="ToDo.js"></script>
</body>
</html>
JS:
let ul = document.querySelector('ul');
newItem = document.querySelector('input');
function output() {
let item = newItem.value;
let newTodo = document.createElement('li');
newTodo.innerText = item;
newTodo.classList.add('todo');
ul.append(newTodo);
}
您的按钮正在提交导致页面刷新的表单。默认情况下,按钮的类型为 submit
。
看起来您实际上并不需要该表单,因此您可以将其删除或在按钮上设置类型:
<button type="button" onclick="output()">Add</button>
我刚刚学会了如何创建和追加项目。我想练习使用按钮提交要附加的文本。它有效,但是,该页面似乎随后立即刷新并从列表中删除了文本。我做错了什么?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To Do List</title>
<link rel="stylesheet" href="ToDo.css">
</head>
<body>
<h1>To Do:</h1>
<ul>
<li class="todo">Create another todo.</li>
</ul>
<form>
<input type="text" placeholder="Add another item!">
<button onclick="output()">Add</button>
</form>
<script src="ToDo.js"></script>
</body>
</html>
JS:
let ul = document.querySelector('ul');
newItem = document.querySelector('input');
function output() {
let item = newItem.value;
let newTodo = document.createElement('li');
newTodo.innerText = item;
newTodo.classList.add('todo');
ul.append(newTodo);
}
您的按钮正在提交导致页面刷新的表单。默认情况下,按钮的类型为 submit
。
看起来您实际上并不需要该表单,因此您可以将其删除或在按钮上设置类型:
<button type="button" onclick="output()">Add</button>