event.which

event.which返回类型:Number

描述:对于键盘事件或鼠标事件,此属性指示了被按下的特定的键或按钮。

  • 增补版本:1.1.3event.which

event.which属性规范化了event.keyCodeevent.charCode。建议针对键盘输入,观察event.which。欲了解更多细节,请参阅 event.charCode on the MDN

event.which还规范化了鼠标按键按下(mousedownmouseup事件)对于左键报告1,对于中间报告2,对于右键报告3。请用event.which代替event.button

示例:

记录哪个键被按下了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!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>

演示:

记录哪个鼠标键被按下了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!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>

演示: