如何捕获Enter键按? [英] How to capture Enter key press?

查看:213
本文介绍了如何捕获Enter键按?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的HTML页面中,我有一个文本框供用户输入搜索关键字。当他们单击搜索按钮时,JavaScript函数将生成一个URL并在新窗口中运行。

In my HTML page, I had a textbox for user to input keyword for searching. When they click the search button, the JavaScript function will generate a URL and run in new window.

当用户通过鼠标单击搜索按钮时,JavaScript函数正常工作,但是当用户按下ENTER键时没有响应。

The JavaScript function work properly when the user clicks the search button by mouse, but there is no response when the user presses the ENTER key.

function searching() {            
            var keywordsStr = document.getElementById('keywords').value;
            var cmd ="http://XXX/advancedsearch_result.asp?language=ENG&+"+ encodeURI(keywordsStr) + "&x=11&y=4";
            window.location = cmd;
        }

    <form name="form1" method="get">
             <input name="keywords" type="text" id="keywords" size="50" >
             <input type="submit" name="btn_search" id="btn_search" value="Search" 
onClick="javascript:searching(); return false;" onKeyPress="javascript:searching(); return false;">
             <input type="reset" name="btn_reset" id="btn_reset" value="Reset">
    </form>


推荐答案

表格方法



正如scoota269所说,你应该使用 onSubmit ,因为在文本框上按下输入最可能会触发表单提交(如果在表单内)

Form approach

As scoota269 says, you should use onSubmit instead, cause pressing enter on a textbox will most likey trigger a form submit (if inside a form)

<form action="#" onsubmit="handle">
    <input type="text" name="txt" />
</form>

<script>
    function handle(e){
        e.preventDefault(); // Otherwise the form will be submitted

        alert("FORM WAS SUBMITTED");
    }
</script>



文本框方法



如果你想要在输入字段上有一个事件,那么你需要确保你的 handle()将返回false,否则表单将被提交。

Textbox approach

If you want to have an event on the input-field then you need to make sure your handle() will return false, otherwise the form will get submitted.

<form action="#">
    <input type="text" name="txt" onkeypress="handle(event)" />
</form>

<script>
    function handle(e){
        if(e.keyCode === 13){
            e.preventDefault(); // Ensure it is only this code that rusn

            alert("Enter was pressed was presses");
        }
    }
</script>

这篇关于如何捕获Enter键按?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆