【问题标题】:<button> with form attribute does not work on IE带有表单属性的 <button> 在 IE 上不起作用
【发布时间】:2014-01-27 02:19:49
【问题描述】:

我的问题是为什么会这样:

<form id="aaa" action"xxx">
</form>
<button form="aaa" type="submit">Button</button>

在 Firefox、Opera、Chrome 中有效,在 IE 11 和 Windows 系统的移动设备中无效?上面的例子什么也没做,按钮似乎不属于表单。

提前谢谢你。

【问题讨论】:

  • 如果要提交表单,按钮标签需要在表单标签内
  • 按钮的 form 属性是 HTML5 的东西...你 (@user3152194) 知道 IE 11 是否支持它吗?我的猜测是没有。
  • 您没有将按钮放在表单中的原因是什么?
  • 可以说我有 2 个具有两个不同操作的表单和一些具有 REQUIRED 属性的输入字段。我无法将表单放入表单中,并且不想让一个按钮单击影响不属于单击按钮形式的输入字段。

标签: html forms button input action


【解决方案1】:

如前所述,理想情况下,按钮应位于表单内。但是,使用表单外部的按钮进行操作的一种方法是让按钮通过 JavaScript 触发表单提交。

一个快速而肮脏的 jQuery 示例来说明:

$('button[form="aaa"]').click(function()
{
    $('#aaa').submit();
});

如果愿意,您可以将其替换为按钮元素上的内联 onclick="" 属性。

【讨论】:

    【解决方案2】:

    这个问题很老,但我想我会分享一下我是如何使用 React 应用程序来解决这个问题的。我需要在提交form 时运行onSubmit 回调,而直接在表单上调用submit 时不会发生这种情况。这是我对问题的快速解决方案。它只考虑表单之外的按钮:

    /**
     * Is the [form] attribute supported?
     */
    const isSupported = (() => {
      const TEST_FORM_NAME = 'form-attribute-polyfill-test';
      const testForm = document.createElement('form');
      testForm.setAttribute('id', TEST_FORM_NAME);
      testForm.setAttribute('type', 'hidden');
      const testInput = document.createElement('input');
      testInput.setAttribute('type', 'hidden');
      testInput.setAttribute('form', TEST_FORM_NAME);
      testForm.appendChild(testInput);
      document.body.appendChild(testInput);
      document.body.appendChild(testForm);
      const sampleElementFound = testForm.elements.length === 1;
      document.body.removeChild(testInput);
      document.body.removeChild(testForm);
      return sampleElementFound;
    })();
    
    /**
     * If it's not, listen for clicks on buttons with a form attribute.
     * In order to submit the form and have all the callbacks run, we insert
     * a button, click it and then remove it to simulate a submission from
     * inside the form.
     */
    if (!isSupported) {
      window.addEventListener('click', e => {
        const {target} = e;
        const formId = target.getAttribute('form');
        if (target.nodeName.toLowerCase() === 'button' && formId) {
          e.preventDefault();
          const form = document.getElementById(formId);
          const button = document.createElement('button');
          form.appendChild(button);
          button.click();
          form.removeChild(button);
        }
      });
    }
    

    【讨论】:

      【解决方案3】:

      submit 按钮通常用于将数据从表单提交到服务器(不考虑 JavaScript)。由于您示例中的按钮不是表单的一部分,因此它没有要提交的关联数据。

      编辑:注意到form 属性后,用户JayC 的回答是正确的。 Internet Explorer 不支持按钮上的该属性,而其他浏览器则支持。它是尚未实施的 HTML 5 标准的一部分。

      【讨论】:

      • 那么如何制作这样的作品:
      • 多个表单(不相互嵌入)或 JavaScript 将需要执行基本的“从该表单提交数据”之外的任何操作。您要么需要重新设计表单,使它们完全分开,要么需要使用 JavaScript 覆盖默认行为。
      猜你喜欢
      • 1970-01-01
      • 2012-06-29
      • 1970-01-01
      • 2015-11-21
      相关资源
      最近更新 更多