ボタンと一連のテキスト フィールドがあります。キーボードナビゲーションを容易にしようとしています。ここに私が持っているものがあります:
HTML
<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 v 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;
}
});
私が抱えている問題は、Firefox と IE10 (おそらく他のもの) で、ボタンを選択して「ENTER」を押すと、2 つのイベントがトリガーされることです。最初のイベントはフォーカスを次のフィールドに移動し、2 番目のイベントは同じことを行います。「ENTER」キーを十分に速く押すことができないようです。このコードを実行してボタンの「Enter」を押すと、field2 になります。
だから私の質問に:イベントを「ロック」して、複数ではなく1つのイベントのみをトリガーすることは可能ですか?
補足として、これを行うためのより良い方法があれば、私はすべて耳にします。
解決:
私の答えは、推奨されるものの組み合わせであることがわかりました。
- 私は $('#button1').on('keyup'....) を取り除きました。冗長でした。
- $('#button').click(...) 関数内に e.stopImmediatePropigation() を追加しました。これで私の問題は解決しました。
機能したソリューションは次のようになります。
/* 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;
}
});
助けてくれてありがとう..うまくいけば、これは他の人にも役立ちます。乾杯。