最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How pass reference to "this" on href javascript function? - Stack Overflow

programmeradmin1浏览0评论

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?

/

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.

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.

Share Improve this question edited Mar 14, 2012 at 12:43 ixx asked Mar 14, 2012 at 12:32 ixxixx 32.3k41 gold badges137 silver badges237 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 24

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/

subjectively you would be better suited with something like:

<a href="javascript:void(0)" id="myAnchor">My Link</a>

and then to code:

document.getElementById('myAnchor').onclick = function() {
    // this is the <a> in here
    return false; // optional, prevents href from executing at all 
};

this way everything is a little more clear. hope this helps -ck

Better to;

<a href="javascript:void(0)" onclick="alert(this.href);">Link</a>

First, add an ID field to your anchor.

Then...

Using standard Javascript:

<a id="someLink" href="javascript:foo(document.getElementById('someLink'));">

Using jQuery:

<a id="someLink" href="javascript:foo($('#someLink'));">
发布评论

评论列表(0)

  1. 暂无评论