开发者

get the element that triggers a javascript function

开发者 https://www.devze.com 2023-01-14 20:16 出处:网络
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:

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);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消