2013-11-23 39 views

回答

4

试试这个 HTML

<button>Click or keydown?</button> 

脚本

$('button').bind("click keydown", function (evt) { 
    if (evt.type == "keydown" && evt.which == 13) 
     alert("Key 13 pressed"); 
    else if (evt.type == "click") 
     alert("Clicked!"); 
}); 

DEMO

OR

function game(e) { 
alert('game start'); 
} 

$('#YourStartButtonID').click(function(e) { 
    game(e); 
}); 

$(document).keydown(function(e) { 
    if (e.keyCode == 13) { game(e); } 
});​​​ 
+0

这仅适用于当按钮被集中,大部分时间的重点将是''或'document'。 –

+0

我更新了我的答案 –

+0

那么,有两种不同的方式来运行单一行动是唯一的方法吗?如果可能的话,我想要做的事情如下: $('#YourStartButtonID')。click.or.keydown(function(e){ game(e); }); –

1
function startGame(){ /*...*/ }  //Your game-starter 

$("#start").click(startGame);   //Button 
$(document).keydown(function(e){ 
    if(e.keyCode == 13) startGame(); //Enter key 
}); 
0

你可以做到这一点

<script> 
    $(function(){ 
    $('#btn').bind('click',function(){alert(1);}); 
    }); 
    $(document).bind("keydown",function(){if(event.keyCode==13)alert(1);}); 
    </script>