Files
front-end-example/04-dom-events-async/05-form-submit-and-prevent-default/starter.js
2026-03-23 14:56:04 +08:00

20 lines
600 B
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 任务:
// 1. 获取表单、输入框和列表
// 2. 监听 submit 事件
// 3. 用 preventDefault() 阻止默认提交
// 4. 读取输入框内容,创建新 li追加到列表
// 5. 清空输入框
const form = document.getElementById("todo-form")
const input = document.getElementById("todo-input")
const list = document.getElementById("todo-list")
form.addEventListener("submit", function (e) {
e.preventDefault()
const text = input.value.trim()
if (text) {
const li = document.createElement("li")
li.textContent = text
list.appendChild(li)
input.value = ""
}
})