DIV CSS 佈局教程網

jQuery 1.7 的 focus() 陷阱:disabled 元素會直接丟出例外
編輯:JQuery特效代碼     

jQuery 有個 focus() 方法可以設定元素的焦點。在 1.7 以前的版本中,不管對象是不是 disabled 狀態,這個方法都不會報錯——只是當元素被停用時,設定的動作實際上沒有作用。

但到了 1.7,行為變了:如果對象處於 disabled 狀態,呼叫 focus() 會直接丟出例外。

Error: Can't move focus to the control because it is invisible,
not enabled, or of a type that does not accept the focus.

翻譯過來就是:不可見或不可用的元素無法取得焦點。

這裡特別要提一下 IE9:它能自動識別這種情況,在 IE9 下不會報錯,但 IE9 以下的版本全數中彈。

重現範例

<!doctype html>
<html>
<head>
  <title>測試</title>
  <script src="jquery-1.7.min.js" type="text/javascript"></script>
  <script type="text/javascript">
    function fnTest(){
        // try {
            $("#txt").focus();
        // } catch(e) {}
    }
  </script>
</head>
<body>
  <div>
    <input type="text" disabled="disabled" id="txt"/>
    <input type="text" id="txt2"/>
    <input type="button" value="Test" onclick="fnTest()"/>
  </div>
</body>
</html>

為什麼這個小變化容易釀成大問題

因為它中斷的是整個程式流程。如果你的 JavaScript 在 focus() 之後還排了一串要執行的動作,例外一丟,後面的程式全部不會跑,而且症狀往往表現在「 unrelated 」的地方,排查起來格外費工。

建議做法

如果一定要使用最新版的 jQuery,最省事的辦法就是把 xxx.focus() 包成:

try { xxx.focus(); } catch(e) {}

更根本的方式是在呼叫前先檢查狀態:

var $txt = $("#txt");
if ($txt.length && !$txt.is(":disabled") && $txt.is(":visible")) {
    $txt.focus();
}

這樣寫的好處是語意清楚——你想表達的其實是「如果這個欄位可以輸入,就把游標移過去」,那麼就把這個判斷明確寫出來,而不是靠 try/catch 把錯誤吞掉。前者是防禦性設計,後者只是掩蓋症狀。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved