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

<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>

当前回答

在游戏的后期,但您不需要任何JavaScript代码来使用按钮作为按钮。默认行为是提交表单,大多数人没有意识到这一点。类型参数有三个选项:submit(默认)、button和reset。这很酷的一点是,如果您添加了事件处理程序,它将绕过提交表单。

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

其他回答

还有一种方法可以防止在单击按钮时进行提交。 要实现这一点,必须使用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>

默认情况下,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,它也能正常工作。

出于可访问性的原因,我无法使用多个type=submit按钮来实现它。如果表单有多个按钮,但只有一个按钮可以在按Enter键时提交表单,那么唯一的方法是确保其中只有一个按钮是type=submit,而其他按钮是type=button等其他类型。通过这种方式,在浏览器上处理表单时,您可以从键盘支持方面获得更好的用户体验。

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

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

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