Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

javascript - 如何捕获Enter键? [重复](How to capture Enter key press? [duplicate])

This question already has an answer here:

(这个问题已经在这里有了答案:)

In my HTML page, I had a textbox for user to input keyword for searching.

(在我的HTML页面中,我有一个文本框供用户输入要搜索的关键字。)

When they click the search button, the JavaScript function will generate a URL and run in new window.

(当他们单击搜索按钮时,JavaScript函数将生成一个URL并在新窗口中运行。)

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.

(当用户用鼠标单击搜索按钮时,JavaScript功能正常工作,但是当用户按ENTER键时,没有响应。)

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>
  ask by Joe Yan translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

(正如scoota269所说,您应该改用onSubmit ,因为在文本框上按Enter键最有可能触发表单提交(如果在表单内))

<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>

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.

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

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...