阻止按钮提交表单 Javascript [英] Keep button from submitting form Javascript
问题描述
我正在学习 JavaScript,但无法在不提交表单的表单内制作按钮.有一个类似的问题这里但最流行的答案是指定type="button"
在我的情况下不起作用,其他答案涉及 jQuery,我现在想忽略它.
I'm learning JavaScript and am unable to make a button inside of a form that doesn't submit the form. There is a similar question here but the most popular answer to specify type="button"
doesn't work in my case and other answers involve jQuery, which I would like to leave out for now.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript">
function submit(){
alert("Yo")
}
</script>
</head>
<body>
<form name="myForm" onsubmit="submit()">
<input type="button" value="Submit!" onClick="submit()" />
</form>
</body>
</html>
推荐答案
因为你没有使用 type="submit"
你的表单提交任何东西的唯一原因是因为你真的单击按钮时调用 submit() 方法.(嗯,有点.它实际上是 form.submit()
- 你创建的方法是 window.submit()
).
Since you're not using a type="submit"
the only reason your form would submit anything is because you're literally calling the submit() method when the button is clicked. (well, sort of. It's actually form.submit()
- the method you created is window.submit()
).
默认情况下,type="button"
的输入不会进行表单提交,除非您直接调用 form.submit()
By default, an input of type="button"
will not do a form submission unless you literally call form.submit()
这篇关于阻止按钮提交表单 Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!