Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
25
rated 0 times [  28] [ 3]  / answers: 1 / hits: 24587  / 13 Years ago, thu, february 16, 2012, 12:00:00

I expect this to print a because when I call foo(this), the argument seems to be the link tag.



<script type=text/javascript>
function foo (e) {
alert (e .tagName);
}
</script>
<a href=javascript:foo(this)>click</a>


Instead, it prints undefined. If I alert(e) it says object Window. How do I make foo know which element launched it? Without passing/looking up ids.


More From » html

 Answers
13

You should not use href for JavaScript. Bad practice, instead use onclick and this will magically point to the link.



<a href=# onclick=foo(this)>click</a>


You also need to cancel the click action of the link. Either with return false or cancelling the event with preventDefault.



It is better to attach the event with Unobtrusive JavaScript


[#87416] Wednesday, February 15, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mariamiyanab

Total Points: 75
Total Questions: 102
Total Answers: 92

Location: British Indian Ocean Territory
Member since Tue, Feb 22, 2022
2 Years ago
;