如何捕获 Enter 按键?

How to capture Enter key press?(如何捕获 Enter 按键?)
本文介绍了如何捕获 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,因为在文本框上按 Enter 很可能会触发表单提交(如果在表单内)

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 runs

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I can get a text of all the cells of the table using testcafe(如何使用 testcafe 获取表格中所有单元格的文本)
node_modules is not recognized as an internal or external command(node_modules 未被识别为内部或外部命令)
How can I create conditional test cases using Protractor?(如何使用 Protractor 创建条件测试用例?)
PhantomJS and clicking a form button(PhantomJS 并单击表单按钮)
Clicking #39;OK#39; on alert or confirm dialog through jquery/javascript?(在警报上单击“确定或通过 jquery/javascript 确认对话框?)
QunitJS-Tests don#39;t start: PhantomJS timed out, possibly due to a missing QUnit start() call(QunitJS-Tests 不启动:PhantomJS 超时,可能是由于缺少 QUnit start() 调用)