为什么$(this).focus(); 当焦点在jquery中时,将无法在同一元素上工作
最初我试图validation用户输入,当我偶然发现问题时,我无法在聚焦时将焦点的光标固定在元素上。 这是代码
$("#ChapterCode").keydown(function(e){ if(e.keyCode==9 || e.keyCode==13){ if($(this).val()!=""){ ChapterCode(); get_fees(); return true; }else{ $(this).focus(); return false; } } });
这将起作用,因为返回false将禁止在单击TAB时更改焦点。 然而
$("#ChapterCode").focusout(function(e){ if($(this).val()!=""){ ChapterCode(); get_fees(); return true; }else{ e.preventDefault(); $(this).focus(); return false; } });
这不会像模糊任何帮助一样吗? 我添加了e.preventDefault(); 知道它不会工作以防万一。 非常感谢帮助再次感谢。 请不要告诉我创建一个错误消息或类似的东西,因为它根本不可能。
它看起来像是不同的浏览器行为。
在Chrome
它的工作方式就是这样。 您可以在blur
或聚焦范围内设置焦点。
FireFox
不是这个。 您需要将其包装到setTimeout()
。
$("#ChapterCode").focusout(function(e){ if($(this).val()!=""){ ChapterCode(); get_fees(); return true; }else{ var self = $(this); setTimeout(function(){ self.focus(); }, 1); return false; } });
这将把焦点转移到#ChapterCode
。 你不能完全防止盒子失去焦点。 您需要引入一个包含this
引用的变量,可以通过setTimeout()
闭包来访问this
变量。
示例: http : //www.jsfiddle.net/hGjwZ/1/