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

<button>My Button</button>

然而,当我单击它时,它提交了表单。代码如下:

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

所有这个按钮应该做的是一些JavaScript。但即使看起来像上面的代码,它也会提交表单。当我将标签按钮更改为span时,它工作得很好。但不幸的是,它必须是一个按钮。是否有任何方法阻止该按钮提交表单?例如:

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

当前回答

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

这是因为即使表单之外的按钮也充当了提交者的角色(参见W3Schools网站:http://www.w3schools.com/tags/att_button_form.asp)。

换句话说,按钮类型默认为“submit”

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

因此,解决这个问题的一个简单方法是使用按钮类型。

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

其他选项包括在onclick结束时返回false,或者在按钮被单击时返回任何其他处理程序,或者使用< input>标记

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

其他回答

我认为这是HTML最烦人的小特点……该按钮需要为“button”类型,以便不提交。

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

2019年2月5日更新:根据HTML生活标准(以及HTML 5规范):

缺少的值default和无效的值default是Submit 按钮的状态。

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

这是因为即使表单之外的按钮也充当了提交者的角色(参见W3Schools网站:http://www.w3schools.com/tags/att_button_form.asp)。

换句话说,按钮类型默认为“submit”

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

因此,解决这个问题的一个简单方法是使用按钮类型。

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

其他选项包括在onclick结束时返回false,或者在按钮被单击时返回任何其他处理程序,或者使用< input>标记

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

返回错误;在onclick处理程序的末尾将完成这项工作。然而,最好是简单地将type="button"添加到<button> -这样即使没有任何JavaScript,它也能正常工作。

还有一种方法可以防止在单击按钮时进行提交。 要实现这一点,必须使用event.preventDefault()方法。

document.querySelector("button#myButton").addEventListener("click", (event) => { document.getElementById("output-box").innerHTML += "Sorry! <code>preventDefault()</code> won't let you submit this!<br>"; event.preventDefault(); }, false); <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="src/style.css"> </head> <body> <form id="myform"> <label>Label <input /> </label> <button id="myButton">My Button</button> </form> <div id="output-box"></div> <script src="src/script.js"></script> </body> </html>

戴夫·马克尔是对的。来自W3School网站:

始终指定的类型属性 按钮。的默认类型 ie浏览器是“按钮”,而 在其他浏览器中(以及W3C中) 规范)它是“提交”。

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