是否可以像这样嵌套html表单

<form name="mainForm">
  <form name="subForm">
  </form>
</form>

两种形式都适用吗?我的朋友有这个问题,subForm的一部分工作,而另一部分不工作。


当前回答

普通html不允许您这样做。但javascript可以做到。 如果你正在使用javascript/jquery,你可以用一个类来分类你的表单元素,然后使用serialize()来序列化那些你想要提交的项目子集的表单元素。

<form id="formid">
    <input type="text" class="class1" />
    <input type="text" class="class2">
</form>

然后在你的javascript中,你可以这样做来序列化class1元素

$(".class1").serialize();

对于class2你可以这样做

$(".class2").serialize();

对于整个形式

$("#formid").serialize();

或者简单地

$("#formid").submit();

其他回答

第二个表单将被忽略,参见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;
}

一个简单的解决方法是使用iframe来保存“嵌套”表单。 从视觉上看,表单是嵌套的,但在代码方面,它在一个单独的html文件中。

今天,我也遇到了同样的问题,为了解决这个问题我增加了一个用户控件和 在这个控件上,我使用这个代码

<div class="divformTagEx">

</div>

<asp:Literal runat="server" ID="litFormTag" Visible="false">
'<div> <form  style="margin-bottom: 3;" action="http://login.php" method="post" name="testformtag"></form> </div>'</asp:Literal>

并在页面的PreRenderComplete事件中调用此方法

private void InitializeJavaScript()
{
        var script = new StringBuilder();
        script.Append("$(document).ready(function () {");
        script.Append("$('.divformTagEx').append( ");
        script.Append(litFormTag.Text);
        script.Append(" )");
        script.Append(" });");
        ScriptManager.RegisterStartupScript(this, GetType(), "nestedFormTagEx", script.ToString(), true);
    }

我相信这会有帮助。

虽然我没有给出嵌套表单的解决方案(它不可靠地工作),但我确实提出了一个适合我的解决方案:

使用场景:允许一次更改N个项的超表单。它底部有一个“提交全部”按钮。每个项目都有自己的嵌套表单,带有“提交项目# N”按钮。但是不能…

在这种情况下,实际上可以使用单个表单,然后将按钮的名称设为submit_1..submit_N和submitAll并在服务器端处理它,如果按钮的名称是submit_1,则只查看以_1结尾的参数。

<form>
    <div id="item1">
        <input type="text" name="foo_1" value="23">
        <input type="submit" name="submit_1" value="Submit Item #1">
    </div>
    <div id="item2">
        <input type="text" name="foo_2" value="33">
        <input type="submit" name="submit_2" value="Submit Item #2">
    </div>
    <input type="submit" name="submitAll" value="Submit All Items">
</form>

好吧,这算不上什么发明,但确实管用。

即使您可以让它在一个浏览器中工作,也不能保证它在所有浏览器中都能正常工作。所以虽然你可能能让它在某些时候工作,但你肯定不能让它在所有时候都工作。