Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How pass reference to "this" on href javascript function?

Tags:

javascript

I have a link with this href:

href="javascript:foo(this);"

when I call it "this" points to the window object, not the link. How do I pass a reference to the link?

http://jsfiddle.net/xMGKz/

Edit note: The question is how to pass with href, not generally - I know about onclick!

And not copying id and make getElementById, that's not "this", it's DOM search for certain element, no need to make it inline in HTML.

The anwer is: not possible.

like image 766
User Avatar asked Mar 14 '12 12:03

User


People also ask

Can we call a JavaScript function on a href?

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).

Can we pass a function in href?

The anwer is: not possible.

How do you pass a href variable?

href”, append the variable to it (Here we have used a variable named “XYZ”). Then we need to append the value to the URL. Now our URL is ready with the variable and its value appended to it. In the example below, we will append a variable named 'XYZ' and its value is 55.

Can I use onclick on link?

having an onclick event for the link is if you are dynamically creating links within the page that will all call the same function but may not have unique ids.


1 Answers

When you use "javascript: .... " in an href, you are calling this function globaly. Not in the context of the link. You can try with:

<a href="#" onclick="foo(this); return false;">MyLink</a>

http://jsfiddle.net/xMGKz/1/

like image 146
MatuDuke Avatar answered Sep 23 '22 07:09

MatuDuke