在 HTML 中,表单是由 form 元素来表示的,而在 JavaScript 中,表单对应的则是 HTMLFormElement 类型。HTMLFormElement 的属性和方法。
acceptCharset: 服务器能够处理的字符集;等价于 HTML 中的 accept-charset 特性。
action: 接受请求的 URL;等价于 HTML 中的 action 特性。
elements: 表单中所有控件的集合(HTMLCollection)。
enctype: 请求的编码类型;等价于 HTML 中的 enctype 特性。
length: 表单中控件的数量。
method: 要发送的 HTTP 请求类型,通常是”get”或”post”;等价于 HTML 的 method 特性。
name: 表单的名称;等价于 HTML 的 name 特性。
reset(): 将所有表单域重置为默认值。
submit(): 提交表单。
target: 用于发送请求和接收响应的窗口名称;等价于 HTML 的 target 特性。
1 | <!-- 通用提交按钮 --> |
2 | <input type="submit" value="Submit Form"> |
3 | |
4 | <!-- 自定义提交按钮 --> |
5 | <button type="submit">Submit Form</button> |
6 | |
7 | <!-- 图像按钮 --> |
8 | <input type="imgage" src="xxx.jpg"> |
9 | |
10 | <!-- 通用重置按钮 --> |
11 | <input type="reset" value="Resrt Form"> |
12 | |
13 | <!-- 自定义重置按钮 --> |
14 | <button type="reset">Reset Form</button> |
1 | <div> |
2 | <label for="username">姓名</label> |
3 | <input id="username" name="username" type="text"> |
4 | </div> |
5 | <div> |
6 | <label for="age">年龄</label> |
7 | <input id="age" name="age" type="text"> |
8 | </div> |
9 | |
10 | //等价于 |
11 | |
12 | <div> |
13 | <label> |
14 | 姓名 |
15 | <input name="username" type="text"> |
16 | </label> |
17 | </div> |
18 | <div> |
19 | <label> |
20 | 年龄 |
21 | <input type="text" name="age"> |
22 | </label> |
23 | </div> |

当点击姓名和年龄时,文本框就会被选中,两个方法都可以获得同样的效果,通常使用后一种。