When query1.7 encounters a problem with the focus method

  • 2020-03-30 01:28:34
  • OfStack

There isa focus() method in jQuery that can set the focus of an object. In the following version of 1.7, this method will not report an error regardless of whether the object is in the disabed state or not (except that the code setting the focus is invalid when disabled). However, in version 1.7, if the object is in the disabled state, when calling the focus() method, it will report an exception directly:

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

It means: An invisible or unavailable element cannot get focus. (special mention: IE9 is very NB, can automatically recognize this situation, in IE9 will not report an error, but IE9 below the version of all hung.)

<!doctype html>
 <title> test </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(){
   <input type="text" disabled="disabled" id="txt"/>
   <input type="text" id="txt2"/>
   <input type="button" value="Test" onclick="fnTest()"/>

It's a small change, but it's easy to make a big mistake, especially if your js code has a lot of other things to do after focus() :)

If you must use the highest version of jQuery, the most convenient way is to write XXX. Focus (), add a try/catch, become try{XXX. Focus (); } the catch (e) {}

Related articles: