專案網頁要求用Enter代替Tab,寫了簡單jQuery Plugin搞定,在Chrome、Firefox測試OK,改用IE測試卻出現怪異反應。網頁有多個區塊,在輸入區塊某個<input>按Enter,確有Tab之效,焦點順利跳至下一欄位,但另一個查詢區的Grid卻也同時自動呼叫AJAX重新查詢。在下一個<input>按Enter,焦點移動後Gird又再自動查詢,屢試不爽。而問題只發生在IE,測了IE9/10皆然,Chrome、Firefox、Safari、Opera則不會。

想不通為什麼按Enter會讓Grid自動查詢,採消去法逐一移掉可疑元素,歷經抽絲剝繭終於找到元兇 -- 查詢區有個<button> onclick事件裡寫了AJAX重新查詢邏輯,在IE按下Enter鍵似乎會觸發<button> click事件。

以下網頁可在IE重現問題:

<!DOCTYPE html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    <meta charset="utf-8">
    <title>IE Button Focus Issue</title>
</head>
<body>
    <input type="text" value="T1" id='t1' />
    <input type="text" value="T2" id='t2' />
    <br />
    <input type="button" id="b1" value="Button1" />
    <button id='b2'>
        <div>Button2</div>
    </button>
    <script>
        $(function () {
            $('#b1').click(function () { 
              alert("Button1 Clicked!"); 
            });
            $('#b2').click(function () { 
              alert("Button2 Clicked!"); 
            });
            $('#t2').focus().select();
        });
    </script>
</body>
</html>

如上圖所示,焦點停在T2<input>,按下Enter卻觸發Button2 Clicked!

Microsoft Support KB裡有答案:

When the focus is on an HTML form, and the user presses the ENTER key, by default, Internet Explorer treats this action as if the user clicks Submit. However, not all browsers behave the same way, and you may want to disable this behavior. This article demonstrates how to use script to prevent this behavior.

在網頁按下Enter,IE視同使用者按下Submit鈕,此行為與其他瀏覽器不同,故MS KB提供停用的做法。

實驗將Button1改為<input type="submit">,按下Enter後變成Button1 Clicked(Demo),驗證按下Enter時,IE會找到網頁裡第一個Submit鈕,觸發其點擊動作。我的網頁純粹靠AJAX運作,沒有<form>,所以觸發的不是PostBack,而是Client端事件,不然或許我會更快察覺。

專案之所以用<button>而非<input type="button">,在於按鈕規格要求包含圖檔及複雜文字樣式,<input type="button">只能指定純文字,而<button>像是容器,內部能自訂HTML標籤,才具足夠彈性。而我一直誤以為<button>等同<input type="button">,但在IE8+ 標準模式下其實是<input type="submit">,而要指定它不當Submit,需額外指定,寫成<button type="button">。

註: IE8+,標準模式為submit、IE6/7及IE8+相容模式則為button,宜留意其會因模式改變。
Windows Internet Explorer 8 and later. The default value of the type attribute depends on the current document compatibility mode. In IE8 Standards mode, the default value is submit. In other compatibility modes and earlier versions of Windows Internet Explorer, the default value is button. 參考來源

修改加上type="button"後,就可避免Enter觸發<button>囉! [Demo]

這枚茶包是個知難行易的經典案例: 找到問題根源才是重點,解決只是舉手之勞。各位茶包射手們,今天就來回味孫文學說做為總結吧!

謂有某家水管偶生窒礙,家主即雇工匠為之修理。工匠一至,不過舉手之勞,而水管即復回原狀。而家主叩以工值幾何,工匠曰:「五十元零四角。」家主曰:「此舉手之勞,我亦能為之,何索值之奢而零星也?何以不五十元,不五十一元,而獨五十元零四角何為者?」工匠曰:「五十元者,我知識之值也;四角者,我勞力之值也。如君今欲自為之,我可取消我勞力之值,而只索知識之值耳。」家主啞然失笑,而照索給之。


Comments

Be the first to post a comment

Post a comment