2010-04-15 77 views
4

當單擊類「removerow」的錨點時,我有一個需要隱藏的錶行。jquery中的父類選擇器

<tr><td>Product Name</td><td><a class="removerow">Remove</a></td></tr> 

我一直想這一點,但它不工作:

$("a.removerow").click(function(){ 
$(tr > this).hide(); 

});

我怎樣才能選擇整個表格行與「.removerow」的孩子。

我在做什麼錯?

謝謝。

回答

4

jQuery的closest(selector)函數將向上遍歷並返回提供的最近的選擇器。

(如果點擊的元素是相同的給定的選擇,那麼它返回。)

http://api.jquery.com/closest/

$("a.removerow").click(function(e){ 
    $(this).closest('tr').hide(); 
    e.preventDefault(); 
}); 

e.preventDefault()將禁用a元素的默認行爲。

3

jQuery沒有父選擇器,但它的確有parent function

另外,tr不是鏈接的直接父節點。相反,它是向上兩級(td是第一父)

$("a.removerow").click(function(){ 
    // Called twice (first is td, second is tr) 
    $(this).parent().parent().hide(); 
}); 

如果沒有其他tr S IN的層次,你也可以使用

$("a.removerow").click(function(){ 
    // Called twice (first is td, second is tr) 
    $(this).parents('tr').hide(); 
}); 

如果TR上有一類,你可以這樣做:

$("a.removerow").click(function(){ 
    // Called twice (first is td, second is tr) 
    $(this).parents('.ClassNameHere').hide(); 
});