我有一个按钮和一系列文本字段。我正在尝试方便键盘导航。以下是我所拥有的:
<button id="button1">Click me</button>
<input type="text" id="field1" name="field1">
<input type="text" id="field2" name="field2">
<input type="text" id="field3" name="field3">JS/JQUERY . 1.9.1
/* If they click the button */
$('#button1').on('click', function() {
moveToNextInputField(); /* <-- Mystical function to "focus" the next input */
});
/* If they hit "enter" on the button */
$('#button1').on('keyup', function(e) {
if (e.which === 13) {
moveToNextInputField();
}
});
/* Capture keyboard input to limit to Numbers */
$('input').on('keydown', function (e) {
switch(e.which) {
case 48:
case 49:
case 50: /* All numbers, or wanted keys, etc.... */
$(this).data('changed', true);
break;
default:
e.preventDefault(); /* prevent other unwanted keys from doing anything */
break;
}
});
/* Capture keyboard input for keyboard navigation */
$('input').on('keyup', function (e) {
switch (e.which) {
/* other cases to do stuff excluded */
case 13:
moveToNextInputField();
break;
}
});我遇到的问题是,在火狐和IE10 (可能还有其他)中,当我选择按钮并按下"ENTER“时,它会触发2个事件。第一个事件将焦点移到下一个字段,第二个事件执行相同的操作。看来我不能足够快地按下"ENTER“键。当我运行这段代码并在按钮上按下"enter“键时,我就会在field2中结束。
因此,对于我的问题:是否有可能“锁定”一个事件,使其只触发1个事件而不是多个事件?
顺便说一句,如果有更好的方法来做这件事,我会全神贯注的。
解决方案:
我发现我的答案是推荐的东西的组合。
以下是解决方案的效果:
/* If they click the button or press ENTER while focused */
$('#button1').on('click', function(e) {
e.stopImmediatePropigation();
moveToNextInputField(); /* <-- Mystical function to "focus" the next input */
});
/* Capture keyboard input to limit to Numbers */
$('input').on('keydown', function (e) {
switch(e.which) {
case 48:
case 49:
case 50: /* All numbers, or wanted keys, etc.... */
$(this).data('changed', true);
break;
default:
e.preventDefault(); /* prevent other unwanted keys from doing anything */
break;
}
});
/* Capture keyboard input for keyboard navigation */
$('input').on('keyup', function (e) {
switch (e.which) {
/* other cases to do stuff excluded */
case 13:
moveToNextInputField();
break;
}
});谢谢大家的帮助..。希望这对其他人也有帮助。干杯。
发布于 2013-07-10 21:09:12
这很简单,当聚焦按钮并单击enter时,单击事件处理程序和keyup事件处理程序都会触发。
换句话说,聚焦按钮并点击enter将触发按钮上的单击事件,因此请更改如下:
$('#button1').on('click', function() {
moveToNextInputField(); /* <-- Mystical function to "focus" the next input */
});
$('#button1').on('keyup', function(e) {
if (e.which === 13) {
moveToNextInputField();
}
});只想:
$('#button1').on('click', function() {
moveToNextInputField(); /* <-- Mystical function to "focus" the next input */
});因为不需要keyup事件处理程序。
小提琴
作为一个副手,你可以把它缩短为:
$('#button1').on('click', moveToNextInputField);发布于 2013-07-10 21:11:19
您必须注意,单击是一种特殊的事件。它是在必须触发按钮函数时生成的。所以它通常发生在鼠标向下,进入或空间之后。您可以应用很少的解决方案
顺便说一下。我还建议使用keypress而不是keyup - 看这儿。
发布于 2013-07-10 20:56:37
您可以尝试jQuery的延迟执行。无论哪种情况先触发,都可以将延迟对象设置为“已解析”。您可以检查对象的状态,以查看它是否第一次触发挂起,而不是在已解析时触发。
https://stackoverflow.com/questions/17580557
复制相似问题