2011-10-14 130 views
0

我有一個表,其中每一行都有一個CSS ID是這樣的:獲取父元素的jQuery選擇

<table> 
<tr id='1'>...</tr> 
<tr id='2'>...</tr> 
<tr id='3'>...</tr> 
</table> 

成一排,用戶可以點擊一個細胞內的特定元素。我想查找已被點擊的行。

因此,例如:

<tr id='x'><td></td>...<td><div class='someclass'><div class='anotherclass'></div></div></td>...</tr> 

在這種情況下,我想當用戶點擊一類=「anotherclass」元素作出響應。我想獲得包含這個單擊元素的行的id,但我不想使用$(this).parent()。parent()。parent()....等等,因爲有多個級別的父項它變得醜陋。

有沒有辦法使用.parent()多次獲取包含此元素的行?

更新:謝謝大家。這是完美的。

+0

[jquery的?:找到父()* n的嵌套元素]的可能重複(http://stackoverflow.com/questions/7022834/jquery-find-parentn-in-nested-element) –

回答

4

使用closest()

$('.anotherclass').click(function() { 
    alert($(this).closest('tr').prop('id')); 
}); 
1

使用closest

$(".anotherclass").click(function() { 
    console.log($(this).closest("tr").attr("id")); 
}); 

從文檔:

獲取的選擇相匹配,在 當前元素開始的第一個元素和通過DOM樹進展。

1

你可以使用這個。

$('.anotherclass').click(function() { 
    alert($(this).parents('tr').attr("id")); 
});