我有一张表格。在表单的外面,我有一个按钮。一个简单的按钮,像这样:
<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按钮提交一个表单。
这是因为即使表单之外的按钮也充当了提交者的角色(参见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
还有一种方法可以防止在单击按钮时进行提交。
要实现这一点,必须使用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>