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

时间:2022-01-26 20:24:34

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

我有一个,它有一个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 e variable - 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变量——事件数据——来自哪里)。但这一次我只想对上面提到的使用这个函数。我需要将事件数据传递给函数,这样它就可以得到按下的键的代码。我想在内联事件处理程序中做这个。我创建了一个功能:

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)">

<输入onkeydown = " myfunc(这)">

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

<输入onkeydown = " myfunc(this.onkeydown)">

<input onkeydown="myfunc(onkeydown)">

<输入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.

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

1 个解决方案

#1


14  

<input onkeydown="myfunc(event)">

<输入onkeydown = " myfunc(事件)">

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

#1


14  

<input onkeydown="myfunc(event)">

<输入onkeydown = " myfunc(事件)">

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

相关文章