jQuery click event - How to tell if mouse was clicked or enter key was pressed?(jQuery单击事件 - 如何判断是否单击了鼠标或按下了回车键?)
问题描述
我的网站存在可用性问题.我有一组选项卡,每个选项卡都包含一个表单.当您单击选项卡链接时,它会将焦点放在选项卡内容正文中的第一个文本框.鼠标导向的人喜欢这个功能".问题在于,当面向键盘的用户使用键盘上的 TAB 键浏览选项卡时.他们在要查看的选项卡上按回车键,单击事件触发并且选项卡显示,但焦点集中在文本框上,完全调整了它们的选项卡顺序.因此,当他们再次点击选项卡时,他们想转到屏幕上的下一个选项卡,但由于焦点已在表单内移动,他们无法使用键盘轻松进入下一个选项卡.
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.
所以,在点击事件中,我需要确定他们是否真的用鼠标按钮点击了它.这可能吗?我的第一次尝试是这样的:
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 时触发了点击事件.幸运的是,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 上放了一个 demo.感谢所有阅读问题的人.
I put up a demo on jsFiddle as well. Thanks to everyone who read the question.
这篇关于jQuery单击事件 - 如何判断是否单击了鼠标或按下了回车键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:jQuery单击事件 - 如何判断是否单击了鼠标或按下
基础教程推荐
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01