javascript 在内联事件处理程序中传递事件数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3846615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 02:27:00  来源:igfitidea点击:

Passing event data in the inline event handlers

javascripteventsevent-handling

提问by rhino

I have an <input>which has an onkeydowninline event handler. In this handler, I'd like to call a function and pass a special parameter to it - the event data.

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

When I want to handle events (e.g. onmousemove) for the whole document, I use the following code:

当我想处理整个文档的事件(例如 onmousemove)时,我使用以下代码:

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

And it works (although I don't know where the evariable - event data - comes from).
But this time I want to use the function only for the <input>mentioned above.
I need to pass the event data to the function so it can get the pressed key's code. And I want to do it in that inline event handler. I've created a function:

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

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

and tried all of these methods:

并尝试了所有这些方法:

<input onkeydown="myfunc(this)">

<input onkeydown="myfunc(this)">

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

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

<input onkeydown="myfunc(onkeydown)">

<input onkeydown="myfunc(onkeydown)">

But none of them worked, the alert window kept displaying "undefined".
I looked for a solution to my problem in Google, but didn't find anything that could help me solve it.

但是它们都不起作用,警报窗口一直显示“未定义”。
我在 Google 中寻找解决问题的方法,但没有找到任何可以帮助我解决问题的方法。

回答by gblazex

<input onkeydown="myfunc(event)">

<input onkeydown="myfunc(event)">

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