問題描述

我有一張表格在這種形式之外,我有一個按鈕。一個簡單的按鈕,像這樣:

<button>My Button</button>

然而,當我點擊它,它提交表單。以下是代碼:

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

所有這個按鈕應該是一些 JavaScript 。但即使看起來像上面的代碼,它提交了表單。當我更改標籤按鈕以跨越,它的工作完美。但不幸的是,它需要一個按鈕。有沒有辦法阻止該按鈕提交表單?像 e 。 G 。

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

最佳解決方案

我認為這是 HTML 的最煩人的小特點… 那個按鈕需要是類型”button” 為了不提交。

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

次佳解決方案

onclick 處理程序結束時的 return false; 將執行此操作。但是,最好將 type="button"添加到<button> 中,即使沒有任何 JavaScript 也能正常運行。

第三種解決方案

Dave Markle 是正確的。來自 W3School’s website

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

換句話説,您使用的瀏覽器遵循 W3C 的規範。

第四種方案

建議不要使用<Button> 標籤。改用<Input type='Button' onclick='return false;'> 標籤。 (使用”return false” 確實不會發送表單。)

一些 reference material

第五種方案

默認情況下,html 按鈕提交表單。

This is due to the fact that even buttons located outside of a form act as submitters (see the W3Schools website: http://www.w3schools.com/tags/att_button_form.asp)

換句話説,默認情況下,按鈕類型為”submit”

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

Therefore an easy way to get around this is to use the button type.

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

Other options include returning false at the end of the onclick or any other handler for when the button is clicked, or to using an < input> tag instead

要了解更多信息,請查看 Mozilla 開發人員網絡中有關按鈕的信息:https://developer.mozilla.org/en/docs/Web/HTML/Element/button

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇