使用选择框检测交互

如何(使用javascript或jQuery)我可以检测何时从选择框中选择了一个值,即使它与之前选择的选项相同(即没有触发更改事件)。

主要是我需要这个用于鼠标交互,但是一个适用于键盘的解决方案也很方便。

我发现可行的唯一解决方案是通过在mousedown上将select的值设置为其他值来引发change事件。 在标记中我创建了一个额外的选项(即第一个孩子)并使其隐藏(像往常一样隐藏在Chrome / FF / Safari,IE中)。 所以它看起来很好。

  

然后使用jQuery,我们以一种方式绑定changemousedown事件,当mousedown触发时, select其值重置为hidden选项的值。

 $("select").on({ change: function() { console.log($(this).val()); }, mousedown: function() { $(this).val($(":first", this).val()); } });​ 

演示: http //jsfiddle.net/LzNrS/

更新:为了在用户点击select但是决定不选择任何内容时保留所选值,我们可以稍微修改代码添加blur事件和更新mousedown

 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); } });​ 

演示: http //jsfiddle.net/LzNrS/1/

如果您可以将事件处理程序附加到选择框选项元素并单击存储其值,我不知道它是否可以从头顶工作。

使用鼠标,无法使用键盘http://jsfiddle.net/w4DEJ/4/

我认为focus()函数可以帮助你… http://api.jquery.com/focus/