在JavaScript中输入按键事件 [英] Enter key press event in JavaScript

查看:170
本文介绍了在JavaScript中输入按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,包含两个文本框,一个选择下拉菜单和一个单选按钮。当输入键被按下时,我想调用一个javascript函数(用户定义),但是当我按下它时,表单被提交。

输入时,如何防止提交表格

如果(characterCode == 13)
{
return false; //返回false将防止事件冒泡。
}
else
{
return true;

好吧,想象一下你在表单中有以下文本框:

 < input id =scriptBoxtype =textonkeypress =return runScript(event)/> 

为了在按下回车键时从该文本框中运行一些用户定义脚本,并没有提交表单,下面是一些 sample 代码。请注意,此功能不会执行任何错误检查,并且很可能只能在IE中使用。要做到这一点,你需要一个更强大的解决方案,但你会得到一般想法。

  function runScript(e){
if(e.keyCode == 13){
var tb = document.getElementById(scriptBox);
eval(tb.value);
返回false;






$ b

返回函数的值将提醒事件处理程序不要再冒泡事件,并且会阻止keypress事件被进一步处理。


I have a form with two text boxes, one select drop down and one radio button. When the enter key is pressed, I want to call a javascript function (User defined), but when I press it, the form is submitted.

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

解决方案

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. Please note that this function doesn't do any error checking and most likely will only work in IE. To do this right you need a more robust solution, but you will get the general idea.

function runScript(e) {
    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.

这篇关于在JavaScript中输入按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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