如何将事件作为参数传递给 JavaScript 中的内联事件处理程序? [英] How to pass event as argument to an inline event handler in JavaScript?
问题描述
// this e works
document.getElementById("p").oncontextmenu = function(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
};
// this e is undefined
function doSomething(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
<p id="p" onclick="doSomething(e)">
<a href="#">foo</a>
<span>bar</span>
</p>
有人问过一些类似的问题.
There are some similar questions have been asked.
但在我的代码中,我试图获取被点击的子元素,例如 a
或 span
.
But in my code, I'm trying to get child elements who's been clicked, like a
or span
.
那么将 event
作为参数传递给事件处理程序的正确方法是什么,或者如何在不传递参数的情况下在处理程序中获取事件?
So what is the correct way to pass event
as an argument to event handler, or how to get event inside handler without passing an argument?
我知道 addEventListener
和 jQuery
,请提供将事件传递给 inline
事件处理程序的解决方案.
I'm aware of addEventListener
and jQuery
, please provide a solution for passing event to inline
event hander.
推荐答案
传递event
对象:
<p id="p" onclick="doSomething(event)">
获取被点击的子element
(应该与event
参数一起使用:
to get the clicked child element
(should be used with event
parameter:
function doSomething(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
传递元素
本身(DOMElement):
to pass the element
itself (DOMElement):
<p id="p" onclick="doThing(this)">
在 jsFiddle 上查看现场示例.
see live example on jsFiddle.
您可以如上所述指定 event
的名称,但您的处理程序也可以访问 event
参数,如这里: "当事件处理程序被指定为 HTML 属性时,指定的代码被包装成一个具有以下参数的函数".链接中有更多其他文档.
You can specify the name of the event
as above, but alternatively your handler can access the event
parameter as described here: "When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters". There's much more additional documentation at the link.
这篇关于如何将事件作为参数传递给 JavaScript 中的内联事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!