當jQuery1.7遇上focus方法的問題

來源:互聯網
上載者:User

 如果一定要用最高版本的jQuery,最省事的辦法莫過於在寫xxx.focus()時,加一個try/catch,變成try{xxx.focus();}catch(e){}

jQuery中有一個focus()方法能設定對象的焦點,在1.7以下的版本中,不管對象是不是disabed狀態,這個方法都不會報錯(只是當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很NB,能自動識別這種情況,在IE9下不會報錯,但是IE9以下的版本全掛。)  代碼如下:<!doctype html><html> <head> <title>測試</title> <script src="jquery-1.7.min.js" type="text/javascript"></script> <!--<script src="jquery-1.4.4.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> 雖然只是一個小變化,但是卻很容易造成大杯具,特別是你的js代碼,在focus()之後,還有其它很多事情要做時:) 建議:如果一定要用最高版本的jQuery,最省事的辦法莫過於在寫xxx.focus()時,加一個try/catch,變成try{xxx.focus();}catch(e){} 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.