A標籤中href和onclick傳遞this對象的實現方法

在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());
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章