我在我的表中的TD以下錨標記:
<a href="javascript:editAccount()" class="edit">edit</a>
我想找到這個TD的父母我editAccount()函數中,執行以下操作:
function editAccount(){ console.log($(this).parent().parent()); }
不過,我一直在我的控制檯得到空
我在我的表中的TD以下錨標記:
<a href="javascript:editAccount()" class="edit">edit</a>
我想找到這個TD的父母我editAccount()函數中,執行以下操作:
function editAccount(){ console.log($(this).parent().parent()); }
不過,我一直在我的控制檯得到空
你需要傳遞受到質疑
元素<a onclick="editAccount(this)" class="edit">edit</a>
和
function editAccount(elem){ console.log($(elem).parent().parent()); }
,或者使用function.call。
<a onclick="editAccount.call(this)" class="edit">edit</a>
和
function editAccount(){ console.log($(this).parent().parent()); }
使用jQuery綁定事件。
<a class="edit" href="#">edit</a>
和
$(function(){
$('.edit').click(function(e){
e.preventDefault();
console.log($(this).parent().parent());
});
});
謝謝它做到了。 – RazorHead
this
並不是指在該函數的任何信息。
只是一個真實的事件添加到錨:
$('.edit').on('click', function(){
console.log($(this).parent().parent());
return false;
});
而不是使用href="javascript:editAccount()
的,通過jQuery使用標準的事件註冊綁定editAccount
:
$(".edit").on("click", editAccount);
您也可以使用匿名函數,而不是單獨定義editAccount
。
萬一.edit
鏈接動態添加,您可以使用事件委派:
$(document).on("click", ".edit", function (e) {
//prevent following the link if you want
e.preventDefault();
console.log($(this).closest("td"));
});
不要這樣做。使用真實的事件處理程序。您應該*不*使用'href =「javascript:'鏈接。 – meagar
我永遠不會這樣做,但不幸的是,在這個項目中,事件處理程序完全不能工作,這就是爲什麼我必須做替代方法... – RazorHead