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
290 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中输入按键事件(Enter key press event in JavaScript)

I have a form with two text boxes, one select drop down and one radio button .

(我有一个带有两个文本框的form ,一个选择下拉菜单和一个单选按钮 。)

When the enter key is pressed, I want to call a Javascript function (User defined), but when I press it, the form is submitted.

(当按下Enter键时,我想调用Javascript函数(用户定义),但是当我按下它时,将提交表单。)

How do I prevent the form from being submitted when the enter key is pressed?

(按下Enter键后,如何防止提交form ?)

  ask by Shyju translate from so

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

1 Reply

0 votes
by (71.8m points)
if(characterCode == 13)
{
    return false; // returning false will prevent the event from bubbling up.
}
else
{
    return true;
}

Ok, so imagine you have the following textbox in a form:

(好的,假设您的表单中包含以下文本框:)

<input id="scriptBox" type="text" onkeypress="return runScript(event)" />

In order to run some "user defined" script from this text box when the enter key is pressed, and not have it submit the form, here is some sample code.

(为了在按下Enter键时从此文本框中运行某些“用户定义”脚本,而不让其提交表单,下面是一些示例代码。)

Please note that this function doesn't do any error checking and most likely will only work in IE.

(请注意,此功能不执行任何错误检查,很可能仅在IE中有效。)

To do this right you need a more robust solution, but you will get the general idea.

(为此,您需要一个更强大的解决方案,但是您将获得一般的想法。)

function runScript(e) {
    //See notes about 'which' and 'key'
    if (e.keyCode == 13) {
        var tb = document.getElementById("scriptBox");
        eval(tb.value);
        return false;
    }
}

returning the value of the function will alert the event handler not to bubble the event any further, and will prevent the keypress event from being handled further.

(返回该函数的值将警告事件处理程序不要再使事件冒泡,并且将防止进一步处理keypress事件。)

NOTE: (注意:)

It's been pointed out that keyCode is now deprecated .

(已经指出, keyCode 现在已弃用 。)

The next best alternative which has also been deprecated .

(接下来的最佳替代品which也被弃用 。)

Unfortunately the favored standard key , which is widely supported by modern browsers, has some dodgy behavior in IE and Edge .

(不幸的是,受现代浏览器广泛支持的受青睐的标准key 在IE和Edge中具有某些躲避行为 。)

Anything older than IE11 would still need a polyfill .

(IE11之前的任何版本都仍需要polyfill 。)

Furthermore, while the deprecated warning is quite ominous about keyCode and which , removing those would represent a massive breaking change to untold numbers of legacy websites.

(此外,尽管已过时的警告对于keyCodewhich是非常不祥的,但删除这些警告将代表着无数旧版网站的巨大突破。)

For that reason, it is unlikely they are going anywhere anytime soon.

(因此, 他们不太可能很快就去任何地方。)


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

...