检测与选择框的交互 [英] Detecting interaction with select box
问题描述
主要是我需要这个用于鼠标交互,但是一个适用于键盘的解决方案也是非常方便的。
我发现可行的唯一解决方案是通过将选择
的值设置为其他的值,导致 change
事件鼠标按下
。在标记中,我创建了一个额外的选项(即第一个孩子),并将其隐藏(像平常一样在Chrome / FF / Safari,IE中完全隐藏)。所以它看起来很好。
< select>
< option style =display:none>< / option>
< option>第一个< / option>
< option>第二个< / option>
< option>第三< / option>
然后使用jQuery绑定改变
和 mousedown
事件,当 mousedown
触发器时, select
将其值重置为隐藏选项的值。
$(select) .on({
pre>
change:function(){
console.log($(this).val());
},
mousedown:function(){
$(this).val($(:first,this).val());
}
});
DEMO: http:/ /jsfiddle.net/LzNrS/
$ b 更新:为了在用户点击<$ c时保留选定的值$ c>选择但决定不选择任何东西,我们可以修改一些代码,添加blur
事件并更新mousedown
。var special =; //特殊的隐藏选项值
var value =; //临时变量
$(select)。on({
change:function(){
console.log($(this).val());
},
mousedown:function(){
if(this.value == special){
$(this).val(value);
return;
}
value = this.value;
$(this).val(special);
},
blur:function(){
if (this.value == special)
$(this).val(value);
}
});
DEMO: http:/ /jsfiddle.net/LzNrS/1/
How (using javascript or jQuery) can I detect when a value has been selected from a select box, even if it's the same option as was previously selected (i.e. no change event is fired).
Mainly I need this for mouse interraction, but a solution that works for keyboard too would be handy.
解决方案The only solution I found workable is to cause
change
event by setting the value ofselect
to some other onmousedown
. In the markup I created one extra option (i.e. the first child) and made it hidden (hides perfectly in Chrome/FF/Safari, IE as usual). So it looks fine.<select> <option style="display: none"></option> <option>First</option> <option>Second</option> <option>Third</option> </select>
Then using jQuery we bind
change
andmousedown
events in a way that whenmousedown
triggers,select
resets its value to the value of the hidden option.$("select").on({ change: function() { console.log($(this).val()); }, mousedown: function() { $(this).val($(":first", this).val()); } });
DEMO: http://jsfiddle.net/LzNrS/
UPDATE: In order to preserve the selected value when user has clicked on
select
but decided not the choose anything, we can modify the code a bit addingblur
event and updatingmousedown
.var special = ""; // special hidden option value var value = ""; // temporary variable $("select").on({ change: function() { console.log($(this).val()); }, mousedown: function() { if (this.value == special) { $(this).val(value); return; } value = this.value; $(this).val(special); }, blur: function() { if (this.value == special) $(this).val(value); } });
DEMO: http://jsfiddle.net/LzNrS/1/
这篇关于检测与选择框的交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!