简体   繁体   English

如何检测JavaScript上的输入文本按下键

[英]How to detect input-text pressed key on javascript

I have this simple document: 我有这个简单的文件:

   <!DOCTYPE html>
      <html>
        <body>
        <input id="mytext" onkeypress="myfun(e)"></input>
        <p id="demo"></p>
        <script> function myfun(e){ 
                if(e.keyCode==13) alert('Enter Key Pressed');}
        });
        </script>
        </body>
      </html>

what I want is: when user press enter key on mytext, show an alert to inform the user like this message : Enter Key Pressed 我想要的是:当用户在mytext上按Enter键时,显示一条警报以通知用户,例如此消息: Enter Key Pressed

I did every thing like above, But it doesn't work and no any alert is shown when enter pressed on mytext. 我做了上面的每件事,但是那行不通,在mytext上按Enter键也没有任何警报显示。

Help Please!.. 请帮助!..

You can add an event listener to listen for the onkeypress event: 您可以添加事件侦听器以监听onkeypress事件:

document.getElementById('mytext').addEventListener('keypress', function(e) {
    if(e.keyCode == 13) alert('Enter Key Pressed');
});

Also, input tag's don't have a closing tag. 另外,输入标签没有结束标签。 Here's a live example 这是一个生动的例子

If you want to call it inline as a handler, try this: 如果要以处理程序的形式内联调用它,请尝试以下操作:

 <input id="mytext" onkeypress="myfun(event)"> <p id="demo"></p> <script> function myfun(event){ var key = event.keyCode || event.which; if(key === 13) alert('Enter Key Pressed'); } </script> 

You must use event as a parameter to make sure it works correctly as a handler. 您必须使用event作为参数,以确保它可以作为处理程序正常工作。 Now, get's the key code and check if it's 13, then alerts. 现在,获取关键代码并检查它是否为13,然后发出警报。

Your code works when you replace myfun(e) with myfun(event). 当您用myfun(event)替换myfun(e)时,您的代码有效。 I also corrected some syntactical errors. 我还纠正了一些语法错误。

 <html>
    <body>
        <input id="mytext" onkeypress="myfun(event)"></input>
        <p id="demo"></p>
        <script> 
            function myfun(e){ 
                    if(e.keyCode==13) alert('Enter Key Pressed');
            };
        </script>
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM