日期:2014-05-16  浏览次数:20342 次

js中回车事件的捕捉

下面给一个例子,回车触发按钮的onclick事件。
<html>
<head><title>keydown</title></head>
<script>
function strdown(event){

?????? if(event.keyCode==13){
??????????? //event.keyCode=0;?? //取消回车
??????????? document.getElementByIdx("str").click();
??????????? return false;
??????? }
}
function test(){
??? alert("ok");
}

</script>

<body onkeydown="strdown(event)">
<input type="button" id="str" onclick="test()" value="button"/>
</body>
</html>
再来看一个用jquery写的例子。
<html>
<head><title>keydown</title>
<script type='text/javascript' src='jquery-1.3.1.min.js' ></script>
</head>
<script>
$(document).ready(function(){
??? $(document).keydown(function(event){? //这里如果写成$(window),在ie下面就不会起作用
? ??? if(event.keyCode==13){
??????????????? document.getElementByIdx("str").onclick();
??????????????? return false;
??????? }
??? });
});
function test(){
??? var s = document.getElementByIdx("a").value;
??? alert(s);
}
</script>
<body >
<input type="text" id="a" />
<input type="button" id="str" onclick="test()" value="button"/>
</body>
</html>