2010-10-02 195 views
10

我有一个<input>,它有一个onkeydown内联事件处理程序。在这个处理程序中,我想调用一个函数并将特殊参数传递给它 - 事件数据。在内联事件处理程序中传递事件数据

当我要处理事件(如的OnMouseMove)整个文档,我用下面的代码:

document.onmousemove=function(e) { 
// here I can make a good use of the 'e' variable, 
// for example extract the mouse coordinates from it 
} 

和它的作品(虽然我不知道在哪里e变量 - 事件数据 - 来自)。
但是这次我只想使用上面提到的<input>的功能。
我需要将事件数据传递给函数,以便它可以获取按下的键的代码。我想在内联事件处理程序中执行此操作。我创建了一个功能:

function myfunc (e) { 
    var evt=window.event?event:e; 
    var code=evt.keyCode; 
    alert (code); 
} 

,并试图所有这些方法:

<input onkeydown="myfunc(this)">

<input onkeydown="myfunc(this.onkeydown)">

<input onkeydown="myfunc(onkeydown)">

但没有一次成功,警告窗口不停显示“未定义”。
我在Google寻找解决我的问题的方法,但没有找到任何可以帮助我解决问题的方法。

回答

14

<input onkeydown="myfunc(event)">

function myfunc (e) { 
    e = e || window.event; 
    var code = e.keyCode; 
    alert (code); 
} 
+0

真的谢谢:)很多我不知道的全球'event'变量。现在它完美的工作,再次感谢。 – rhino 2010-10-02 18:36:13

+0

你应该在进入javascript事件处理之前真的阅读一篇论文,因为它可能会变得混乱,特别是如果你处理IE。无论如何,我很高兴能够提供帮助。 – galambalazs 2010-10-02 18:38:11

+1

在IE7&和IE 8上不起作用 – Luckyy 2014-04-02 08:55:55

相关问题