A標籤中通過href和onclick傳遞的this對象實現思路

來源:互聯網
上載者:User

在blog的後台管理中允許為一個分類添加一個地址,但是不好添加onclick事件。想傳遞當前對象給一個函數,於是就將這個URL寫成"Javascript:shoControlSidebar(this)",可是結果發現這並不可行,傳遞過去的參數是一個對象,但是卻得不到任何其他資訊。我想得到的是innerText,而這個this並非指向它所在的A標籤。

這是<a href="Javascript:shoControlSidebar(this)">和<a href="javascript:void(0)" onclick="shoControlSidebar(this)">不同的地方。

當使用onclick="shoControlSidebar(this)"的時候,解譯器會給他封裝一個匿名函數,變成了:
複製代碼 代碼如下:
a.onclick = function anonymous()
{
shoControlSidebar(this);
}

這個this指的就是a這個對象,而使用href的方式時,由於是一個地址,這個this就無處可指了。
複製代碼 代碼如下:
<a href="javascript:void(0);" onclick="test(this);">A標籤測試</a>

複製代碼 代碼如下:
想擷取A 中的innerHTML
如果href="test(this);" 不但擷取不到值,而且程式將退出,href引向不對。

複製代碼 代碼如下:
function test(obj){
alert(obj);
//js
alert(obj.innerHTML);
//jquery
alert($(obj).html());
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.