Enter键触发搜索

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lb245557472/article/details/86369909
<!DOCTYPE html>
<html>
	<head>
	<!--引入线上jQuery库,(必须引用,或者直接下载后引用)-->
		<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
		<script>
		//third method
			$(document).keypress(function(event){
	  			if(event.keyCode ==13){
	    		$("#codeSubmit").trigger("click");
	  			}
			});
		/*
			$(document).ready(function(){ 
				//first method
				//$("#errorCode").keydown(function (e) {//当按下按键时
				//	if (e.which == 13) {//.which属性判断按下的是哪个键,回车键的键位序号为13
				//		$('#codeSubmit').trigger("click");//触发搜索按钮的点击事件
				//	}
				//});
				
				//second method
				$("#errorCode").on('keypress',function(event){
					if(event.keyCode == 13){
						//alert("hello");
						$('#codeSubmit').trigger('click')}
				});
			})
		*/
			function copyText(){
				//document.getElementById("lastname").value=document.getElementById("firstname").value;
				alert("查询成功!");
				//do something
			}
		</script>
	</head>
	<body>
		<div id="errorForm">
			Field1: <input type="search" name="errorCode" id="errorCode" value="" placeholder="请输出错误码进行查询"><br>
			Field2: <input type="search1" name="errorCode1" id="errorCode1" value="" placeholder="请输出错误码进行查询" onkeypress="copyText()"><br>
			Field3: <button id="codeSubmit" value="" onclick="copyText()">查询</button><br><br>
		</div>
	</body>
</html>

用浏览器打开你会看到如下图所示结果(点击enter键和点击查询按钮):
在这里插入图片描述
用jQuery的有三种方法,第三种的是全局方法,监听应用于页面的所有的输入框(因为没有绑定元素),其他两种只会触发绑定的输入框;还有一种input的自带的点击事件属性,添加onkeypress属性,绑定函数也是可以实现的。

猜你喜欢

转载自blog.csdn.net/lb245557472/article/details/86369909