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.
The anwer is: not possible.
In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).
The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the <a> tag will not be a hyperlink. Tip: You can use href="#top" or href="#" to link to the top of the current page!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With