2010-03-19 165 views
2

我有一個jQuery的簡單位,它顯示當前行下方的行(如果選中)。jQuery單擊td行不發射事件

我想要什麼,如果所有的<td>元素,但一個發射這種方法。

作品在整個<tr>

 $(document).ready(function(){ 

     $("#report > tbody > tr.odd").click(function(){ 
      $(this).next("#report tr").fadeToggle(600); 
     }); 
    }); 

要像做(不工作)

$(document).ready(function(){ 

     $("#report > tbody > tr.odd > td.selected").click(function(){ 
      $(this).next("#report tr").fadeToggle(600); 
     }); 
    }); 

回答

4

你需要的東西是這樣的:

$(document).ready(function(){ 
    $("#report tr:not(.odd)").hide(); 
    $("#report tr:first-child").show(); 

    $("#report > tbody > tr.odd > td.selected").click(function(){ 
     $(this).closest("tr").next("tr").fadeToggle(600); 
    }); 
}); 

既然你點擊一個TD,需要設法讓下一行之前上到該行。這個選擇器在大多數情況下也應該是相同的:#report td.selected。既然你無法逃脫與兄弟姐妹在#report之內,#report tr也可能只是tr在你的next()

4

在你不工作的代碼,$(this)<td>元素。

因此,$(this).next("#report tr")不符合任何內容。 (因爲<td>元素沒有<tr>元素作爲兄弟)

您需要將其更改爲$(this).closest('tr').next("#report tr")才能找到「叔叔」元素。您也可以撥打.parent()而不是.closest('tr'),但即使您將click處理程序綁定到<td>的子項,仍會呼叫.closest繼續工作。