在keypress上,JQuery UI点击事件触发两次 [英] JQuery UI click event fires twice on keypress

查看:122
本文介绍了在keypress上,JQuery UI点击事件触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTML

<button id="clickMe" tabindex=0>Click Me!</button>

JS

$('#clickMe').button();
$('#clickMe').click(function() {
    alert('hey');
});

$(document).keypress(function (e) {
    var key = e.keyCode ? e.keyCode : e.which;
    //detect when the user has hit enter
    if (key == 13) {
        //click the focused element
        $(document.activeElement).click();
    }
});

当你点击标签来关注按钮时,为什么这会发出两次警报和输入作为按键事件,但只有用鼠标点击按钮才会触发一次?

Why does this alert fire twice when you hit tab to focus the button and enter for the keypress event, but only fires once when you click the button with the mouse?

示范

编辑标签 + 输入在IE 10中完全不起作用

EDIT: tab + enter doesn't work at all in IE 10

推荐答案

因为点击回车时焦点在一个按钮上本机触发点击事件。您获得按键事件,然后您再次触发点击事件。

Because hitting "Enter" when focus is on a button triggers the "click" event natively. You also get a "keypress" event, and from that you trigger the "click" event again.

这篇关于在keypress上,JQuery UI点击事件触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆