Does a <button> TYPE have to be defined?

2019-03-03 09:10发布

When using the button tag, does the type attribute have to be defined, or is it semantic to just have?

<button>Click Me</button>

2条回答
The star\"
2楼-- · 2019-03-03 10:03

No, you don't have to specify it, it defaults to the value submit.

See the HTML 4.x specification:

type        (button|submit|reset) submit -- for use as form button --
                                  ^^^^^^ default value

Compare with the action attribute for forms where it says #REQUIRED instead of giving a default value.

action      %URI;          #REQUIRED -- server-side form handler --
查看更多
Explosion°爆炸
3楼-- · 2019-03-03 10:10

As @Quentin’s answer explains, the type attribute is not required and it defaults to submit. There is no change to this in HTML5. However, the situation is slightly more complicated.

If the element appears outside any form element, the above still applies, but there is no form to submit. HTML5 clarifies this by describing the functionality so that it becomes clear that if there is no “form owner” (either an enclosing form element or a form element explicitly associated with the button element with an HTML5 attribute), there is no action – except as programmed with scripting, of course.

In effect, this means that outside a form element, a button element defaults to type=button functionally. This implies that if a button element that has type defaulted changes its context (e.g., gets wrapped inside a form element), its functionality changes. Therefore, for clarity and safety, it is better to explicitly specify the type attribute, e.g. <button type=button> or <button type=submit>.

查看更多
登录 后发表回答