HTML
<div class="button">
<button class="btn">1</button>
<button class="btn">2</button>
<button class="btn">3</button>
</div>
<div class="form">
<form action="" id="submit">
<input type="text" id="num" number/>
</form>
</div>
<div id="show"></div>
JQUERY
$(function($){
//on click
$('.btn').click(function(){
var me = $(this);
$('#show').html(me.text());
});
//on keypress
$(window).keypress(function(k){
switch (k.keyCode) {
// user presses the "1"
case 49:
$('#show').html(1);
break;
// user presses the "2"
case 50:
$('#show').html(2);
break;
// user presses the "3"
case 51:
$('#show').html(3);
break;
}
});
//on submit
$('#submit').submit(function(e){
e.preventDefault();
var data = $('#num').val();
$('#show').html(data);
$('#num').val('');
})
});
答案 0 :(得分:2)
在默认情况下尝试使用event.preventDefault()
.on输入按键事件
<强>更新强>
对于输入中的所有键阻止,在按键功能的第一行添加event.preventDefault()
$(window).keypress(function(k) {
k.preventDefault() //its prevent all keyinput
switch (k.keyCode) {
case 49:
$('#show').html(1);
break;
// user presses the "2"
case 50:
$('#show').html(2);
break;
// user presses the "3"
case 51:
$('#show').html(3);
break;
default:
k.preventDefault() //its prevent keypress other than 1,2,3
}
});
答案 1 :(得分:2)
尝试在按键事件中检查输入框的焦点属性,如:
if (!$('#num').is(':focus')) {
switch (k.keyCode) {
case 49:
$('#show').html(1);
break;
// user presses the "2"
case 50:
$('#show').html(2);
break;
// user presses the "3"
case 51:
$('#show').html(3);
break;
default:
}
}
您可以在我已更新的fiddle中查看。