using <a href="a(this")>

  • Thread starter Oliver Saunders
  • Start date
O

Oliver Saunders

can someone please tell me why everytime i try and pass this to a js
function i can't seem to use it for anything:

<html>
<head>
<script language="javascript">
function a(fromlink) {
alert(fromlink.nodeName); // outputs undefined
alert(fromlink.nodeType); // outputs undefined
alert(fromlink.parentNode); // outputs undefined

// i might as well be writing:
alert(fromlink.blahblah_not_a_member);
}
</script>
</head>
<body>
Some body text<br />
<a href="javascript:a(this)">This is a link</a>
</body>
</html>

what am i doing wrong? this is driving me mad
 
M

Martin Honnen

Oliver Saunders wrote:

<a href="javascript:a(this)">This is a link</a>

You want
<a href="#"
onclick="a(this); return false;">
Inside of an event handler the this object is the element the event
handler is attached to.
A javascript: URL in a href attribute is not an event handler.
 
L

Lee

Oliver Saunders said:
can someone please tell me why everytime i try and pass this to a js
function i can't seem to use it for anything:

<html>
<head>
<script language="javascript">
function a(fromlink) {
alert(fromlink.nodeName); // outputs undefined
alert(fromlink.nodeType); // outputs undefined
alert(fromlink.parentNode); // outputs undefined

// i might as well be writing:
alert(fromlink.blahblah_not_a_member);
}
</script>
</head>
<body>
Some body text<br />
<a href="javascript:a(this)">This is a link</a>
</body>
</html>

what am i doing wrong? this is driving me mad

The "javascript:" pseudo-protocol functions similarly to the "http:"
protocol, except that the new contents for the current window come
from the output of your a() function, instead of from a web server.
If the output happens to be void, then the contents are unchanged.
You're abusing this mechanism for the side-effect of executing the
function.

Your a() function executes in the context of the window whose content
it is replacing, so "this" is a reference to the window, not to the
link. You can see that if you add the line:

alert(fromlink);
 
O

Oliver Saunders

You want
<a href="#"
onclick="a(this); return false;">
Inside of an event handler the this object is the element the event handler is attached to.
A javascript: URL in a href attribute is not an event handler.

ah huh thank you.
Your a() function executes in the context of the window whose content
it is replacing, so "this" is a reference to the window, not to the
link. You can see that if you add the line:

alert(fromlink);


yes actually I did notice that. thanks for clearing that up.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top