繁体   English   中英

当箭头按下时,jQuery更改事件在选择时触发

[英]jQuery change event firing on select when arrows pressed

我已经在很多地方看到jQuery在选择上的更改事件只会触发模糊或鼠标点击,但是当我尝试它时,事件也会在每个箭头键按下时触发。 当箭头用于选择选项时,我试图让更改事件不会触发。 例如:

<select size="4" id="more" name="more" required="required">
    <option value="0">No</option>
    <option value="1">Yes</option>
    <option value="2">Maybe</option>
    <option value="3">No clue</option>
</select>

$('#more').on('change', function(event){
    alert('hi');
});​

这个小提琴展示了在以下情况下发生的事件: http//jsfiddle.net/McWatt/x5cTr/7/

根据jQuery change()页面,如果我选择选项,然后使用箭头选择一个选项,更改事件不应该开始,直到选择失去焦点(至少我是如何阅读它)。 实际上,我看到每次按箭头键都会触发更改事件。

http://api.jquery.com/change/

对于选择框,复选框和单选按钮,当用户使用鼠标进行选择时会立即触发事件,但对于其他元素类型,事件将延迟,直到元素失去焦点。

这种行为是否已更改,或者我不了解其功能?

更新:我误读了jQuery文档,尽管它们可能更清晰。 我已经接受了导致我实现的答案。 对于我的问题的实际解决方案,我将keydown事件绑定到select,如果使用了箭头,则将数据属性设置为false。 然后在更改绑定中,如果data属性为true,我将条件设置为仅在更改时执行代码。 这不是最佳解决方案,因为如果使用箭头它会有效地杀死更改回调代码,但由于有另一种方法可以触发功能(通过按钮),我可以使用此功能。

Update2:这是一个工作小提琴: http//jsfiddle.net/McWatt/BR8QQ/

// prevent change event being fired on arrow keys
$('#more').data('activation', 'activated').bind({
    keydown: function(event) {
        if(event.which === 38 || event.which === 40){
            $(this).data('activation', 'paused');
        }
    },
    click: function(event) {
        if($(this).data('activation') === 'paused'){
            $(this).data('activation', 'activated');
            $(this).trigger('change');
        }
    },
    change: function(event) {    
        if($(this).data('activation') === 'activated'){
            var time = new Date();
            $('#changed').text(event.type + ": " + time.getTime());
        }
    }
});

看起来不准确。 据我所知,它与香草change事件没有什么不同。

基本上,只要基于文本的输入在其值更改后失去焦点,它就会触发事件。 只要单击一个复选框(或在聚焦时使用空格键切换),它就会触发事件。 每当选择一个单选按钮时(通过单击,空格键,箭头键......),它就会触发该事件。 每当更改选择框时(通过选择,箭头键......),它也会触发事件。

在这方面,jQuery与vanilla JS没有什么不同。

也许你可以在那里添加点击检查

$('#more').change(function(event){
    $(this).click(function(event){
    var time = new Date();
    $('#changed').text(event.type + ": " + time.getTime());
    });
 });​

http://jsfiddle.net/x5cTr/13/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM