问题描述

我有一张表格在这种形式之外,我有一个按钮。一个简单的按钮,像这样:

<button>My Button</button>

然而,当我点击它,它提交表单。以下是代码:

<form id="myform">
    <input />
</form>
<button>My Button</button>

所有这个按钮应该是一些 JavaScript 。但即使看起来像上面的代码,它提交了表单。当我更改标签按钮以跨越,它的工作完美。但不幸的是,它需要一个按钮。有没有办法阻止该按钮提交表单?像 e 。 G 。

<button onclick="document.getElementById('myform').doNotSubmit();">My Button</button>

最佳解决方案

我认为这是 HTML 的最烦人的小特点… 那个按钮需要是类型”button” 为了不提交。

<button type="button">My Button</button>

次佳解决方案

onclick 处理程序结束时的 return false; 将执行此操作。但是,最好将 type="button"添加到<button> 中,即使没有任何 JavaScript 也能正常运行。

第三种解决方案

Dave Markle 是正确的。来自 W3School’s website

Always specify the type attribute for the button. The default type for Internet Explorer is “button”, while in other browsers (and in the W3C specification) it is “submit”.

换句话说,您使用的浏览器遵循 W3C 的规范。

第四种方案

建议不要使用<Button> 标签。改用<Input type='Button' onclick='return false;'> 标签。 (使用”return false” 确实不会发送表单。)

一些 reference material

第五种方案

默认情况下,html 按钮提交表单。

This is due to the fact that even buttons located outside of a form act as submitters (see the W3Schools website: http://www.w3schools.com/tags/att_button_form.asp)

换句话说,默认情况下,按钮类型为”submit”

<button type="submit">Button Text</button>

Therefore an easy way to get around this is to use the button type.

<button type="button">Button Text</button>

Other options include returning false at the end of the onclick or any other handler for when the button is clicked, or to using an < input> tag instead

要了解更多信息,请查看 Mozilla 开发人员网络中有关按钮的信息:https://developer.mozilla.org/en/docs/Web/HTML/Element/button

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛