点击清除(Clear)按钮时,表单竟然提交了!
今天在编写 Angular + Material Design 表单时,遇到一个奇怪的问题:点击清除按钮时,表单竟然被提交了!
表单结构非常简单:
- 用户名和密码输入框
- 提交按钮(Submit)
- 清除按钮(Clear)
但点击清除按钮时,触发了意外的表单提交行为。

代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Title</title> </head> <body> <form onsubmit="onSubmit()"> <label for="username">Username:</label> <input id="username" name="username" type="text" /> <label for="password">Password:</label> <input id="password" name="password" type="password" /> <button type="submit">Submit</button> <button onclick="clear()">Clear</button> </form>
<script> function onSubmit() { const username = document.getElementById("username").value; const password = document.getElementById("password").value; console.log("username:", username); console.log("password:", password); }
function clear() { document.getElementById("username").value = ""; document.getElementById("password").value = ""; } </script> </body> </html>
|
原因分析
后来仔细查阅MDN文档发现,form
表单中button
的默认type是submit
,而我的代码中没有为清除按钮指定button的type,所以点击清除按钮时,同时触发了清除和提交两个操作。
submit
:默认值,点击按钮时提交表单。
reset
:点击按钮时重置表单中的所有字段。
button
:点击按钮时不执行任何操作,这种类型的button需要用户自己添加事件处理函数。
解决办法
方法一
为清除按钮指定type为button
,这样点击清除按钮时就不会触发表单提交了。
1
| <button type="button" onclick="clear()">Clear</button>
|
方法二
为清除按钮指定type为reset
,这样做的好处是:1. 语义更清晰,2. 不需添加额外的事件处理函数。
1
| <button type="reset">Clear</button>
|
参考
关于form中button的更多细节,请参考MDN