[英]How pass reference to “this” on href javascript function?
I have a link with this href: 我有这个href的链接:
href="javascript:foo(this);"
when I call it "this" points to the window object, not the link. 当我称之为“this”指向窗口对象,而不是链接。 How do I pass a reference to the link? 如何传递对链接的引用?
http://jsfiddle.net/xMGKz/ http://jsfiddle.net/xMGKz/
Edit note : The question is how to pass with href, not generally - I know about onclick! 编辑注释 :问题是如何通过href传递,而不是一般 - 我知道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. 而不是复制id和make getElementById,这不是“this”,它是DOM搜索某个元素,不需要在HTML中内联。
The anwer is: not possible. 答案是:不可能。
When you use "javascript: .... " in an href, you are calling this function globaly. 当你在href中使用“javascript:....”时,你正在调用这个函数globaly。 Not in the context of the link. 不在链接的上下文中。 You can try with: 您可以尝试:
<a href="#" onclick="foo(this); return false;">MyLink</a>
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 希望这有助于确定
更好;
<a href="javascript:void(0)" onclick="alert(this.href);">Link</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.