是否可以像这样嵌套html表单
<form name="mainForm">
<form name="subForm">
</form>
</form>
两种形式都适用吗?我的朋友有这个问题,subForm的一部分工作,而另一部分不工作。
是否可以像这样嵌套html表单
<form name="mainForm">
<form name="subForm">
</form>
</form>
两种形式都适用吗?我的朋友有这个问题,subForm的一部分工作,而另一部分不工作。
当前回答
即使您可以让它在一个浏览器中工作,也不能保证它在所有浏览器中都能正常工作。所以虽然你可能能让它在某些时候工作,但你肯定不能让它在所有时候都工作。
其他回答
第二个表单将被忽略,参见WebKit的代码片段:
bool HTMLParser::formCreateErrorCheck(Token* t, RefPtr<Node>& result)
{
// Only create a new form if we're not already inside one.
// This is consistent with other browsers' behavior.
if (!m_currentFormElement) {
m_currentFormElement = new HTMLFormElement(formTag, m_document);
result = m_currentFormElement;
pCloserCreateErrorCheck(t, result);
}
return false;
}
HTML5 <input>表单属性可以是解决方案。 从http://www.w3schools.com/tags/att_input_form.asp:
表单属性是HTML5中的新属性。 指定<input>元素属于哪个<form>元素。此属性的值必须是同一文档中<form>元素的id属性。
场景:
input_Form1_n1 input_Form2_n1 input_Form1_n2 input_Form2_n2
实现:
<form id="Form1" action="Action1.php" method="post"></form>
<form id="Form2" action="Action2.php" method="post"></form>
<input type="text" name="input_Form1_n1" form="Form1" />
<input type="text" name="input_Form2_n1" form="Form2" />
<input type="text" name="input_Form1_n2" form="Form1" />
<input type="text" name="input_Form2_n2" form="Form2" />
<input type="submit" name="button1" value="buttonVal1" form="Form1" />
<input type="submit" name="button2" value="buttonVal2" form="Form2" />
在这里你可以找到浏览器的兼容性。
注意,不允许嵌套FORM元素!
http://www.w3.org/MarkUp/html3/forms.html
https://www.w3.org/TR/html4/appendix/changes.html#h-A.3.9 (html4规范指出从3.2到4的嵌套表单没有变化)
https://www.w3.org/TR/html4/appendix/changes.html#h-A.1.1.12 (html4规范指出,从4.0到4.1,嵌套表单没有变化)
https://www.w3.org/TR/html5-diff/ (html5规范指出从4到5的嵌套表单没有变化)
https://www.w3.org/TR/html5/forms.html#association-of-controls-and-forms评论到“此功能允许作者在缺乏对嵌套表单元素的支持的情况下工作”,但没有引用这是在哪里指定的,我认为他们是在假设我们应该假设它是在html3规范中指定的:)
另一种解决这个问题的方法是,如果你使用一些服务器端脚本语言,允许你操纵发布的数据,就是这样声明你的html表单:
<form>
<input name="a_name"/>
<input name="a_second_name"/>
<input name="subform[another_name]"/>
<input name="subform[another_second_name]"/>
</form>
如果你打印发布的数据(我将在这里使用PHP),你会得到一个这样的数组:
//print_r($_POST) will output :
array(
'a_name' => 'a_name_value',
'a_second_name' => 'a_second_name_value',
'subform' => array(
'another_name' => 'a_name_value',
'another_second_name' => 'another_second_name_value',
),
);
然后你可以这样做:
$my_sub_form_data = $_POST['subform'];
unset($_POST['subform']);
你的$_POST现在只有你的“主表单”数据,你的子表单数据存储在你可以随意操作的另一个变量中。
希望这能有所帮助!
总之,没有。一个页面中可以有多个表单,但它们不应该嵌套。
来自html5工作草案:
4.10.3 form元素 内容模型: 流内容,但没有表单元素后代。