admin管理员组文章数量:1135660
// 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>
// 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.
But in my code, I'm trying to get child elements who's been clicked, like a
or span
.
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?
edit
I'm aware of addEventListener
and jQuery
, please provide a solution for passing event to inline
event hander.
- developer.mozilla.org/en/docs/DOM/EventTarget.addEventListener – Paul S. Commented May 6, 2013 at 17:54
- 5 Is there a good reason for using inline event handlers rather than switching to addEventListener? en.wikipedia.org/wiki/Unobtrusive_JavaScript – Xotic750 Commented May 6, 2013 at 17:56
- 6 @Xotic750 For me yes, no need to care about re-binding them manually everytime when dynamically loading or reloading html through ajax for example. – Wadih M. Commented Aug 31, 2019 at 20:07
- 2 Inline handlers are more declarative – Sergey Ponomarev Commented Aug 14, 2021 at 16:24
5 Answers
Reset to default 312to pass the event
object:
<p id="p" onclick="doSomething(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);
}
to pass the element
itself (DOMElement):
<p id="p" onclick="doThing(this)">
see live example on jsFiddle.
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.
You don't need to pass this
, there already is the event
object passed by default automatically, which contains event.target
which has the object it's coming from. You can lighten your syntax:
This:
<p onclick="doSomething()">
Will work with this:
function doSomething(){
console.log(event);
console.log(event.target);
}
You don't need to instantiate the event
object, it's already there. Try it out. And event.target
will contain the entire object calling it, which you were referencing as "this" before.
Now if you dynamically trigger doSomething() from somewhere in your code, you will notice that event
is undefined. This is because it wasn't triggered from an event of clicking. So if you still want to artificially trigger the event, simply use dispatchEvent
:
document.getElementById('element').dispatchEvent(new CustomEvent("click", {'bubbles': true}));
Then doSomething()
will see event
and event.target
as per usual!
No need to pass this
everywhere, and you can keep your function signatures free from wiring information and simplify things.
Update 2022-10-30:
I have contacted someone from WHATWG, and another way it could be done is below, although some IDE's report it as "obsolete" which it's not. You could pass the "event" keyword (no capital E) in your caller's argument list, in any position, and use it as such.
Below would work, a, b, c and d being extra arguments to pass if any, to demonstrate the order doesn't matter:
<p onclick="doSomething(a,b,event,c,d)">
And in your function definition, you would capture it accordingly:
function doSomething(arg1, arg2, arg3, arg4, arg5){} //arg3 would contain the event
And access the usual properties, in this case since we wired event with arg3:
console.log(arg3.target)
Since inline events are executed as functions you can simply use arguments.
<p id="p" onclick="doSomething.apply(this, arguments)">
and
function doSomething(e) {
if (!e) e = window.event;
// 'e' is the event.
// 'this' is the P element
}
The 'event' that is mentioned in the accepted answer is actually the name of the argument passed to the function. It has nothing to do with the global event.
Here is how I would do it to prevent users from copying and pasting invalid characters into input text fields:
function validatePaste(el, e) {
var regex = /^[a-z .'-]+$/gi;
var key = e.clipboardData.getData('text')
if (!regex.test(key)) {
e.preventDefault();
return false;
}
}
This function is located inside <script>
tags and it is called like:
<input type="text" onpaste="validatePaste(event)">
This would answer the question perfectly without having to worry about deprecation issues.
function doSomething(e){
// instead of e.target, use just 'e'
console.log(e)
}
<p id="p" onclick="doSomething(this)">
<a href="#">foo</a>
<span>bar</span>
</p>
本文标签: How to pass event as argument to an inline event handler in JavaScriptStack Overflow
版权声明:本文标题:How to pass event as argument to an inline event handler in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736775993a1952339.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论