2010-06-28 69 views
3

我想知道如何在按回车键时启动javacsript函数。我正在尝试创建一个名为handleEnter(event, fn)的函数。如何在按回车键时调用js函数

我想使用的功能,在输入栏上例如:

onkeypress="return handleEnter(event, update_field(this)); 
+0

我想我已经解决了这个问题。 – Rapidz 2010-06-30 10:37:06

回答

6

为了您的函数调用onkeypress事件,检查事件的.keyCode或价值。其中,看看它是否等于13

function handleEnter(e, func){ 
    if (e.keyCode == 13 || e.which == 13) 
     //Enter was pressed, handle it here 
} 

IIRC,IE使用event.which,Firefox将使用e.keyCode来查看哪个键被按下。

+4

我相信键码是13而不是8? – 2010-06-28 18:12:57

+0

你说得对,8是退格。固定。 – Michal 2010-06-28 18:28:03

+0

您不能在JavaScript中使用'function'作为参数名称或变量名称。 – 2010-06-29 09:36:40

1

我想我已经解决了它。

在输入字段我有:

<input onkeypress="return handleEnter(event, update_field, this, 'task');" type="text" /> 

对于我的功能我有:

function handleEnter(e, callback, obj, field){ 

    if(e){ 
     e = e 
    } else { 
     e = window.event 
    } 

    if(e.which){ 
    var keycode = e.which 
    } else { 
    var keycode = e.keyCode 
    } 


    if(keycode == 13) { 
     var tstid = $(obj).parent().find('input[type=hidden]').val(); 
     callback.apply(this, [field, $(obj).val(), tstid ]); 
    } 
} 

,它似乎是现在的工作很好。