javascript - 表单中的按钮导致它自动提交

标签 javascript html

HTML 版本最近有变化吗(比如从 ie7 到 IE8?) 我注意到以下变化让我有些烦恼 - 我有一个类似于此的代码:

<form method="POST" action="/admin/modify">
<input type="text"/>
<button onclick="dosomething()">Press</button>
</form>
<script type="text/javascript">
function doSomething(){
// doesn't matter what actually
}
</script>

这段代码让我感到奇怪的是,通过按下表单内的按钮,我只想执行一些 javascript 操作,但最终它会导致表单也被提交,即使我不愿意这样做.
所以——是真的吗?如果是这样,我如何在 from 中执行一些 java 脚本 actoin 但防止自动提交表单?

最佳答案

根据 W3schools , submit 是 IE 8 中 button 元素的新默认操作:

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

因此,如果您不指定类型,则该表单将在所有浏览器中提交,但不会在 IE 7 中提交。

这应该有效:

<button type="button" onclick="dosomething()">Press</button>

关于javascript - 表单中的按钮导致它自动提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2440043/

相关文章:

javascript - 具有 JavaScript 功能的 HTML 按钮可更改 BG 颜色

javascript - Gulp 二级 Assets

html - 如何在新页面上继续 CSS 列表?

javascript - 将输入限制为数字和 。在输入字段

javascript - 从 JavaScript 中的命名管道读取

html - 添加大量文本时 tr/td 拉伸(stretch)

javascript - 尝试通过 jQuery getJSON jsonp 读取远程 URL,但它不起作用

javascript - 当开发人员工具关闭时,AngularJS 代码不执行 InternetExplorer

javascript - 一种获得完整字符串的方法?

javascript - CSS动画向前然后向后闪烁