jQuery检测ENTER键按下事件

学习在jQuery中检测ENTER键示例。这是常识,如果您必须检测浏览器中按下的键,则必须检入键码(ascii)值。简单容易。当您不知道如何正确使用此功能时,就会出现问题。例如,您是否需要绑定按键或按键?ENTER键的ascii值是多少?

1. jQuery检测ENTER键

注意,“ ENTER”键由ASCII码“ 13”表示。检查此ASCII图表

要检查用户是在网页上还是在任何输入元素上按下ENTER键,可以将keypresskeydown事件绑定到该元素或文档对象本身。然后在bind()功能中检查所按按键的键码是否为13。

如果按键的ASCII码为13,则按“ ENTER”键;否则,将按下其他键。

阅读更多:按键事件和按键事件之间的区别

2. jQuery检测在文本框中按下的ENTER键

$('#someTextBox').keypress(function(event){
	var keycode = (event.keyCode ? event.keyCode : event.which);
	if(keycode == '13'){
		alert('You pressed a "enter" key in textbox');	
	}
});

3. jQuery检测在文档对象上按下的ENTER键

$(document).keypress(function(event){
	var keycode = (event.keyCode ? event.keyCode : event.which);
	if(keycode == '13'){
		alert('You pressed a "enter" key in somewhere');	
	}
});
在Firefox中,您必须使用event.which来获取键码;IE支持event.keyCodeevent.which

4. jQuery检测ENTER键–尝试一下

<html>
	<head>
		<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
	</head>
	<body>
		<h1>Detect ENTER key with jQuery</h1>
		<label>TextBox Area: </label>
		<input id="someTextBox" type="text" size="40" />
		<script type="text/javascript">
			//Bind keypress event to textbox
			$('#someTextBox').keypress(function(event){
				var keycode = (event.keyCode ? event.keyCode : event.which);
				if(keycode == '13'){
					alert('You pressed a "enter" key in textbox');	
				}
				//Stop the event from propogation to other handlers
				//If this line will be removed, then keypress event handler attached 
				//at document level will also be triggered
				event.stopPropagation();
			});
			
			//Bind keypress event to document
			$(document).keypress(function(event){
				var keycode = (event.keyCode ? event.keyCode : event.which);
				if(keycode == '13'){
					alert('You pressed a "enter" key in somewhere');	
				}
			});
		</script>
	</body>
</html>

学习愉快!

saigon has written 1440 articles

Leave a Reply