get the element that triggers a javascript function
i want to know if i can access the element that triggers a function in javascript. i know... it's kinda hard to understand but maybe if you see the following code you'll get what i try to explain:
CODE HTML:
<a href="javascript:myFunction(this)">link</a>
CODE JS:
function myFunction(linkElement) {
console.log(linkElement);
}
Obviously that doesn't work, but the idea is that i would like to have access to the element that triggers (or calls) the function so that the console.log would give me the 'a' element.
I know you can use an ID and send the ID to the function and easily recover the el开发者_JAVA技巧ement, but it would be much nicer if i can use something more relative like the 'this' statement.
Change this
<a href="javascript:myFunction(this)">link</a>
to this
<a href="#" onclick="myFunction(this); return false;">link</a>
How about event.target
? https://developer.mozilla.org/en-US/docs/Web/API/Event/target
The target property of the Event interface is a reference to the object that dispatched the event.
function myFunction() {
console.log(event.target);
}
精彩评论