jQuery click事件-如何判断是单击鼠标还是按下Enter键? [英] jQuery click event - How to tell if mouse was clicked or enter key was pressed?

查看:274
本文介绍了jQuery click事件-如何判断是单击鼠标还是按下Enter键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的网站上有可用性问题.我有一组选项卡,每个选项卡都包含一个表单.当您单击选项卡链接时,它将焦点集中于选项卡内容主体中的第一个文本框.面向鼠标的人喜欢这种功能".问题是,面向键盘的用户使用键盘上的TAB键浏览选项卡时.他们在要查看的选项卡上按回车键,触发click事件并显示选项卡,但焦点集中在文本框上,从而完全调整了其选项卡顺序.因此,当他们再次点击选项卡时,他们想转到屏幕上的下一个选项卡,但是由于焦点已移到表单内部,因此他们无法轻松地使用键盘转到下一个选项卡.

I have a usability concern on a web site of mine. I have a set of tabs, each containing a form. When you click on the tab link, it gives focus to the first textbox in the tab content body. Mouse-oriented people love this "feature". The problem is when keyboard-oriented users use the TAB key on their keyboard to go through the tabs. They hit enter on the tab they want to look at, the click event fires and the tab shows up, but focus is given to the textbox, adjusting their tab order completely. So when they hit tab again, they want to go to the next tab on the screen, but since focus was moved inside the form, they can't easily get to the next tab using the keyboard.

因此,在click事件中,我需要确定他们是否确实使用鼠标按钮对其进行了单击.这可能吗?我的第一次尝试是:

So, inside the click event I need to determine if they actually clicked on it with a mouse button. Is this possible? My first attempt was this:

$("#tabs li a").click(function(e) {
  var tab = $(this.href);
  if(e.keyCode != 13)
    $("input:first", tab).focus();
});

但是keyCode始终为0.which属性也始终为0.请帮忙!

But keyCode is always 0. The which property is also always 0. Please help!

推荐答案

这是我想出的解决方案,它非常简单.我将keydown捕获在选项卡链接上,并在keyCode为13时触发了click事件.幸运的是, trigger 函数使我们可以将额外的参数传递给事件处理程序...

Here's the solution I came up with, it's surprisingly simple. I trapped keydown on the tab links, and triggered the click event when keyCode was 13. Luckily, the trigger function allows us to pass extra parameters to the event handler...

$("#tabs li a").keydown(function(e) {
  if(e.keyCode == 13) {
    $(this).trigger("click", true);
    e.preventDefault();
  }
});

所以我只需要更改点击处理程序即可接收新参数并使用它...

So I just had to change my click handler to receive the new parameter and use it...

$("#tabs li a").click(function(e, enterKeyPressed) {
  if(enterKeyPressed)
    alert("Enter key");
  else
    alert("Clicked");
});

我也在jsFiddle上放置了演示.感谢阅读问题的每个人.

I put up a demo on jsFiddle as well. Thanks to everyone who read the question.

这篇关于jQuery click事件-如何判断是单击鼠标还是按下Enter键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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