带有& lt; select& gt;的jQuery focus()事件的无限循环元素 [英] Infinite loop of jQuery focus() event with a <select> element
问题描述
我有这个HTML:
<select id="select-one">
<option value="">Choose</option>
<option value="1">House</option>
</select>
<select id="select-two">
<option value="">Choose</option>
<option value="A">Table</option>
</select>
这个带有JQuery的Javascript
And this Javascript with JQuery
$("#select-two").focus( function() {
if( $("#select-one").val() == "" ) {
alert("Fill select-one first!");
return false;
}
});
所以我收到了警报的无限循环,因为在调用alert()
之后,Javascript再次将焦点放在了相同的选择(选择两个)中.
So i am getting a infinite loop with alerts because after call alert()
Javascript puts the focus again in the same select (select-two).
有人可以帮我解决这个问题吗?
Someone can help me to solve this please?
推荐答案
注意:根据您的评论,假定您必须收听焦点事件.
Note: based on your comments, this assumes you must listen to the focus event.
解决方案1-使用blur()
-有效但在Chrome中存在错误
Solution 1 - using blur()
- effective but buggy in Chrome
理论上,focus
事件是不可取消的,因此在这种情况下return false
或event.preventDefault()
将无效.但是,实际上,可以使用blur()
方法撤消该事件.
In theory, the focus
event is not cancelable, so return false
or event.preventDefault()
will have no effect in this case. However, in practice, you can reverse the event by using the blur()
method.
例如:
$('#select-two').on('focus',function () {
if ($("#select-one").val() == "") {
$(this).blur();
alert('Fill select-one first!');
return false;
}
});
请参见 jsFiddle演示
See jsFiddle demo
这有效地防止了在alert
调用之后该字段重新获得焦点,因此不会重复focus
事件.唯一的问题是,即使在该领域不再集中精力,Chrome中的下拉列表仍保持打开状态(请参见演示).
This effectively prevents the field from regaining focus after the alert
call and so the focus
event is not repeated. The only problem is that in Chrome even though the field is not focused anymore, the dropdown remains open (see demo).
解决方案2-使用remove()
和clone()
-昂贵但跨浏览器
Solution 2 - using remove()
and clone()
- costly but cross-browser
如果Chrome的行为有问题,则可以采用更粗略的方法,即从DOM中remove()
select
,clone()
,然后将其重新插入DOM.这将有效地完全重置" select
元素,使其没有焦点并处于关闭状态.
If Chrome's behavior is problematic, you can take a more crude approach, whereby you remove()
the select
from the DOM, clone()
it and then reinsert it into the DOM. This will effectively "reset" the select
element completely, leaving it without focus as well as closed.
例如:
$(document).on('focus','#select-two',function (e) {
if ($("#select-one").val() == "") {
$(this).remove().clone().insertAfter('#select-one');
alert('Fill select-one first!');
return false;
}
});
请参见 jsFiddle演示
See jsFiddle demo
这种方法的好处是它在Chrome中也能很好地工作.这种方法的缺点在于,它涉及到处理DOM的一个非常琐碎的问题.
The upside of this approach is that it works well in Chrome too. The downside of this approach is that it involves manipulating the DOM for a very trivial issue.
这篇关于带有& lt; select& gt;的jQuery focus()事件的无限循环元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!