Quantcast
Channel: Programming – Gea-Suan Lin's BLOG
Viewing all articles
Browse latest Browse all 102

與 的差異

$
0
0

在追奇怪的問題時發現的,實際上是個當年沒學好 (或是太久沒用忘記了),現在回頭重新學的東西,在 Stack Overflow 上很久前就有人問過了:「<button> vs. <input type="button"> -- which to use?」。

我遇到的問題是 <button> 預設會觸發 submit 事件 (<input type="button"> 不會,然後我以為 <button> 也不會)。

而這邊又遇到 <button> 上綁定了 click() 事件的後續行為在 ChromiumFirefox 不同。

我在 click() 事件裡修改某些 input field 後想要觸發 submit() 事件時透過 document.querySelector('#second_submit_button').click() 觸發第二個 submit 按鈕,但在 Chromium 上會走到第一個 submit,而在 Firefox 上則是會走第二個 submit...

不確定這種複雜的行為是怎麼被定義的 (也蠻有機會是沒定義的),所以只先查了比較單純的東西。

首先是現代的 HTML 規格中定義 <button> 的行為是在「The button element」這邊,裡面提到:

The type attribute controls the behavior of the button when it is activated. It is an enumerated attribute with the following keywords and states:

中間列了一張表列出 type 可以設定的值,然後說如果沒有指定 type 的話就是 submit:

The attribute's missing value default and invalid value default are both the Submit Button state.

If the type attribute is in the Submit Button state, the element is specifically a submit button.

知道為什麼後就能夠規劃解法了,解法看起來有兩條路:

第一條是用 <input type="button">,這樣就不會觸發瀏覽器的預設 submit 行為,就不會有後續的分支要處理。

第二條是用 event.preventDefault() 躲開問題,就... 會動。

不過這代表小時候沒學好啊... 如果我記得 <button> 預設會 submit 的話,我就會習慣用 <input type="button">,避免常態性中獎 @_@


Viewing all articles
Browse latest Browse all 102