Javascript:传递事件和元素引用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19857710/
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-27 17:02:35  来源:igfitidea点击:

Javascript: Pass event AND element reference

javascriptfunctioneventsonkeypress

提问by themisterunknown

I want an input field which calls a javascript function, if a key is pressed. But I'm not able to pass the event as well as an element reference. I can either pass the event:

如果按下某个键,我想要一个调用 javascript 函数的输入字段。但是我无法传递事件和元素引用。我可以通过事件:

<input type="text" name="chmod" value="644" onkeypress="chmod(e)">

or pass the element reference:

或传递元素引用:

<input type="text" name="chmod" value="644" onkeypress="chmod(this)">

If I try to pass both there occurs an error:

如果我尝试通过两者,则会出现错误:

<input type="text" name="chmod" value="644" onkeypress="chmod(e, this)">

Uncaught ReferenceError: e is not defined

Is there any way to pass both, the event and a reference to the element?

有没有办法同时传递事件和对元素的引用?

Cheers, Marco

干杯,马可

回答by Sebastien C.

<input type="text" name="chmod" value="644" onkeypress="chmod(event, this)">

回答by Simon

You should have a reference to the element in the event: event.target.

您应该引用事件中的元素:event.target

回答by sroes

I'd do the following:

我会做以下事情:

<input type="text" name="chmod" value="644" onkeypress="chmod">

Then your js:

然后你的js:

function chmod(e) {
    var element = e.target;
    ...
}

回答by matewka

The thiskeyword is already in the function

this关键字已经在功能

<script>
function chmod(e) {
    var elem = this;
}
</script>

<input type="text" name="chmod" value="644" onkeypress="chmod">