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 t开发者_高级运维o 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. E.g.
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.
精彩评论