简体   繁体   中英

Javascript .focus issue in IE for dynamic content

Javascript syntax

for(i in x) { x[i].focus(); }

This works properly in Mozilla and Chrome but gives error in IE.

Error displayed is

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

I tried using try catch block as below

for(i in x) { try { x[i].focus(); } catch(err){ } }

It worked properly, but My system has more than 100 pages and dont know how many times i have used .focus

Kindly help me get rid of this IE problem.

This error happens when you try to focus() an element that can't take focus (as the error says). To get rid of it, implement a method that does the necessary checks before calling focus on the element. Eg

function focusElement(el) {
  var canFocus = !el.disabled &&
                  el.style.display != 'none' &&
                  el.style.visibility != 'hidden';
  if (canFocus) el.focus();
  return canFocus;
}

... then your code would look like:

for (i in x) focusElement(x[i]);

(BTW, 'seems odd that you would focus() more than one element at a time, since only the last element will be left with the focus.)

This could be because for ( i in x ) will also return all other attributes of the x object.

So, if this is an array, it will return length as well, and the code will try to invoke 'focus()' on the integer number which does not exist.

I would modify the code to check on the presence of focus method first.

So: for(i in x) { if (x[i].focus) { x[i].focus(); } }

You may add try/catch as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM