event.which
返回: Number
event.which
描述:对于键盘或鼠标事件,该属性标明了指定的键或者鼠标按键是否被按下了。
加入于: 1.1.3
event.which该event.which规范化了event.keyCode和event.charCode。建议通过观察event.which来了解键盘输入。欲知详情,请阅读event.charCode on the MDN。
event.which也规范化了鼠标按键按下(用于mousedown和mouseup,对左按键报告1,对中按键即滚轮报告2,对右按键报告3)。请使用event.which来代替event.button。
示例
记录哪个键被按下了。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<input id="whichkey" value="type something">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "keydown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
演示结果
记录哪个鼠标按钮被按下了。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>event.which demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<input id="whichkey" value="click here">
<div id="log"></div>
<script>
$( "#whichkey" ).on( "mousedown", function( event ) {
$( "#log" ).html( event.type + ": " + event.which );
});
</script>
</body>
</html>
演示结果