跟我看:HTML 里的表单
表单是访客输入的一组字段:
<form id="message-form">
<label for="name">Your name</label>
<input id="name" type="text" placeholder="Jake">
<label for="message">Message</label>
<textarea id="message" placeholder="Hi! You have an awesome website."></textarea>
<button type="submit">Send message</button>
</form>
<p id="confirmation"></p>
<form>包裹整个表单。<input>是单行字段,<textarea>是多行。<label>是字段标题——靠for和id配对(点标题会跳到字段)。placeholder是灰色提示文字。type="submit"的按钮提交表单。
一点 CSS 让它好看:
form {
display: flex;
flex-direction: column; /* fields stacked vertically */
gap: 8px;
max-width: 400px;
}
input, textarea {
font: inherit;
padding: 10px;
border: 1px solid #d6d3d1;
border-radius: 8px;
}
.error {
border-color: #dc2626 !important;
background-color: #fee2e2;
}
flex-direction: column 把 flexbox 从横向变成纵向:子元素上下排列。
跟我看:JavaScript 里检查
const form = document.getElementById("message-form");
const name = document.getElementById("name");
const message = document.getElementById("message");
const confirmation = document.getElementById("confirmation");
form.addEventListener("submit", (event) => {
event.preventDefault(); // stop the normal submit (the page would reload)
// Clear old error marks
name.classList.remove("error");
message.classList.remove("error");
// Check that fields are filled in
if (name.value.trim() === "") {
name.classList.add("error");
confirmation.textContent = "You forgot your name. 🙂";
return;
}
if (message.value.trim() === "") {
message.classList.add("error");
confirmation.textContent = "So what do you want to tell me? Write something.";
return;
}
// Everything's fine
confirmation.textContent = "Thanks for the message, " + name.value + "! 💌";
form.reset(); // empty the fields
});
新东西:
submit——“表单正在提交”的事件。我们监听表单,不是按钮。event.preventDefault()——“别做平时会做的事。” 没有这个,页面会刷新,脚本来不及运行。.value——字段里输入的内容。.trim()去掉首尾空格(所以 ” ” 算空!)。return——立刻退出函数(没必要继续检查)。
💡
留言去哪了? 现在还到不了任何地方——我们没有服务器接收。我们只检查并说谢谢。但记住这里:第 3 级我们会建真正的服务器和留言板,把这个表单连上去。那时留言真的会保存!
轮到你了 💪
给网站加一个符合项目的表单,带输入检查:
- 🏫 给学校的留言——姓名 + 留言(和示例一样)。
- 🙋 给我写信——姓名 + 留言,可以加”你最喜欢的游戏”字段。
- 🌍 旅行建议——姓名 + “下次该去哪,为什么”。
- ⚽ 训练报名——姓名 + 年龄(
<input type="number">)+ 检查年龄已填且至少 6 岁:if (age.value < 6) { ... }。
⚠️
专业人士的安全习惯: 永远不要信任用户输入的内容。总要检查——空字段、荒谬的年龄、太长的文字。今天是为了礼貌;在真实应用里,这是防攻击的第一道防线。
✅
检查一下: 提交空表单会把字段标红并显示消息。填好的表单会按名字说谢谢并清空。礼貌、友好、专业。
这堂课你要记住
- 表单:
<form>、<input>、<textarea>、<label>,以及带preventDefault()的submit事件。 .value.trim()= 用户输入的内容,去掉周围空格。- 用户输入 永远 要检查——这是安全编程的基础。
© 2026 Ing. Martin Polak / AlgoRhino · 内容使用条款