与选择框检测互动(Detecting interaction with select box)

2019-06-24 05:18发布

如何(使用JavaScript或jQuery的)我可以检测当值已经从选择框中选择,即使是相同的选项以前选择(即不改变事件被触发)。

主要是我需要这个鼠标interraction,但键盘太有效的解决方案将是得心应手。

Answer 1:

我找到可行的唯一解决办法是引起change的值设置事件select上的一些其他mousedown 。 在标记我创建了一个额外的选项(即第一个孩子),并使其隐藏(在Chrome / FF / Safari浏览器,IE像往常一样完全隐藏)。 因此,它看起来不错。

<select>
    <option style="display: none"></option>
    <option>First</option>
    <option>Second</option>
    <option>Third</option>
</select>​

然后使用jQuery我们绑定changemousedown的方式事件时mousedown触发器, select其值重置为隐藏选项的值。

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

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

DEMO: http://jsfiddle.net/LzNrS/1/



Answer 2:

我不知道,如果它只是从我头顶的工作,如果你可以附加一个事件处理程序来选择框中选择元素和点击商店的价值。

与鼠标的操作,不与键盘工作http://jsfiddle.net/w4DEJ/4/



Answer 3:

我认为焦点()函数将帮助you..try这样的: http://api.jquery.com/focus/



文章来源: Detecting interaction with select box