构建完整、无障碍、可用于生产环境的表单。
在 Kodokon 中打开本课表单是几乎所有网页交互的入口:注册、搜索、结账、联系我们。你已经知道一个页面是如何组织的;现在该动手实践了。首先记住黄金法则:每个字段都要有 name 属性,因为它才是发送给服务器的内容,而不是 id。
<form action="/subscribe" method="post">
<label for="email">Email address</label>
<input type="email" id="email" name="email" required>
<button type="submit">Sign up</button>
</form>看看 label / input 这一对:label 的 for 属性指向字段的 id。这个关联对屏幕阅读器至关重要。另外注意 type="email":浏览器会免费帮你校验格式,并在移动端弹出合适的键盘。其他类型每天都能派上用场:number、date、password、checkbox、radio。
<label for="country">Country</label>
<select id="country" name="country" required>
<option value="">-- Choose a country --</option>
<option value="fr">France</option>
<option value="ca">Canada</option>
</select>
<label for="message">Your message</label>
<textarea id="message" name="message" rows="5"></textarea>最后一个角色:button。它接受三种类型:submit(提交表单)、reset(清空字段)和 button(本身什么都不做——用 JavaScript 给它接上逻辑)。思考练习:在一篇博客文章的表单里,你加了一个不能发送数据的“预览”按钮。你会给它设成哪种类型?答案:type="button"。
<form action="/contact" method="post">
<label for="topic">Subject</label>
<select id="topic" name="topic">
<option value="support">Technical support</option>
<option value="billing">Billing</option>
</select>
<button type="submit">Send</button>
<button type="button" id="preview-btn">
Preview
</button>
</form>