[英]How pass reference to “this” on href javascript function?
我有這個href的鏈接:
href="javascript:foo(this);"
當我稱之為“this”指向窗口對象,而不是鏈接。 如何傳遞對鏈接的引用?
編輯注釋 :問題是如何通過href傳遞,而不是一般 - 我知道onclick!
而不是復制id和make getElementById,這不是“this”,它是DOM搜索某個元素,不需要在HTML中內聯。
答案是:不可能。
當你在href中使用“javascript:....”時,你正在調用這個函數globaly。 不在鏈接的上下文中。 您可以嘗試:
<a href="#" onclick="foo(this); return false;">MyLink</a>
主觀上你會更適合以下的東西:
<a href="javascript:void(0)" id="myAnchor">My Link</a>
然后編碼:
document.getElementById('myAnchor').onclick = function() {
// this is the <a> in here
return false; // optional, prevents href from executing at all
};
這樣一切都會更加清晰。 希望這有助於確定
更好;
<a href="javascript:void(0)" onclick="alert(this.href);">Link</a>
首先,向錨點添加ID字段。
然后...
使用標准Javascript:
<a id="someLink" href="javascript:foo(document.getElementById('someLink'));">
使用jQuery :
<a id="someLink" href="javascript:foo($('#someLink'));">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.