问题
I just read the following at http://w3fools.com/#html_forms:
Non-block-level elements (such as
<input>
) are not valid directly inside<form>
tags until HTML5.
I had never heard of anything along these lines, and every basic HTML tutorial I've seen seems to be just fine with putting input tags directly inside a form tag. So my question has three parts:
- Is the above statement legitimate?
- Why is this the case? (Was it simply an oversight, or were the creators of the HTML spec trying to prevent specific problems by creating this rule?)
- What is the recommended way to construct a form with inputs? (Are we just supposed to create a div or a table directly inside the form tag?)
回答1:
It's standards pedantics.
- The statement is legitimate as far as the standard goes: in HTML 4.01, the definition for <form> specifies that it may only contain block elements or
<script>
. As far as what every browser in the world allows, it's fine. - I can only guess that they consider
<form>
to not be a layout tag at all, and they want all inline elements to be contained inside a block element. - Yes, you're supposed to place a
<div>
,<table>
,<p>
, or some other block presentational element inside the<form>
.
回答2:
The above statement is true. In HTML the <input> tag is not a valid element of the <form> tag. In order to make this validate, you need to enclose the <input> tag with either a <fieldset> or <div>. Which is demonstrated below.
<form action="/" method="post">
<fieldset>
Field: <input type="text" name="field" />
<br />
<input type="submit" value="Submit" />
</fieldset>
</form>
回答3:
First of all I'd like to mention that it's not really surprising that HTML tutorials teach you to do things wrong – HTML was practically designed to accept any and every way of doing things. You can leave tags unclosed, you can nest them improperly and whatnot, which is one of the reasons I personally use XHTML.
That statement seems to be true, but because of how HTML is designed, it does not matter in practise. XHTML probably prohibits this.
Form isn't really a container of any sort. It seems like the creators of the HTML spec were fond of things like block-level elements you should wrap everything inside of. This is just my view on it, though, but as far as I've noticed, non-block-level elements shouldn't be used without a proper container for them.
It's exactly like you shouldn't put non-block-level elements in a <blockquote>
. Block-level-elements are containers for other elements.
A div, a table – I think even a <p>
does the thing here.
回答4:
Well, according to the HTML 4.01 specification (specifically section 17.3), this is technically true. However, I don't know of any web browser that would actually give you a problem over it.
来源:https://stackoverflow.com/questions/5439078/why-is-an-input-tag-not-allowed-directly-within-a-form-tag