2011-04-10 90 views
0

TD隱藏單元格,我有以下表格:檢索使用jQuery

<table id="mytable"> 
<tr> 
<th class="hidden">id</th> 
<th>name</th> 
</tr> 
<tr> 
<td class="hidden">87</td> 
<td>Isle of Palms</td> 
</tr> 
</table> 

,然後這個jQuery代碼隱藏ID列:

<script> 
$(function() { 
$('.hidden').hide(); 
}); 
</script> 

我需要獲得ID單元隱藏值時我點擊任何一行,但我找不到合適的選擇器。任何幫助將不勝感激。感謝名單。

回答

0

試試這個:

$('tr').click(function() { 

    var id = $(this).find('td.hidden').html(); 
}); 

UPDATE

$('tr').click(function() { 

    var id = $(this).find('td.hidden:first').html(); 
}); 

如果有很多列,要選擇的第一個,你可以使用:first。請記住,這將爲您表中的所有行添加單擊事件。我想你只對你體內的行感興趣,你的例子沒有。所以我會做這個:

<table id="mytable"> 
    <thead> 
    <tr> 
     <th class="hidden">id</th> 
     <th>name</th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr> 
     <td class="hidden">87</td> 
     <td>Isle of Palms</td> 
    </tr> 
    </tbody> 
</table> 

,然後設置單擊事件TBODY行

$('tbody tr').click(function() { 

    var id = $(this).find('td.hidden:first').html(); 
}); 

希望幫助!

+0

返回null。感謝無論如何;) – Jorge 2011-04-10 21:23:30

+0

呃...實際上你的代碼適用於我發佈的例子。對我最後的評論感到抱歉。但它不適合我真正的問題。我使用了一個有15列的表格,其中7個是隱藏的,我需要獲得第一個隱藏列,它是id。最好的祝福。 – Jorge 2011-04-10 21:36:33

+0

請看我的更新。 – 2011-04-10 21:46:57

0

我會假設你我的<td class="hidden">87</td>87

.text()您可以在<tr/>註冊一個單擊處理程序,然後找到你<td/>

$("tr").click(function(){ 
    var $idCell = $(this).find("td.hidden"); 
    if($idCell.length == 1) 
    { 
     var id = $idCell.text(); 
    } 
}); 

編輯

一稍微好一點的選項可能是使用.filter(),因此您只註冊具有chil的事件處理程序d <td class="hidden"/>

$("tr").filter(function(){ 
    return $(this).children("td.hidden").length == 1; 
}).click(function(){ 
    alert($(this).find("td.hidden").text()); 
}); 
+0

這將工作!或者他實際上可以編寫符合W3C標準的ad和tbody。然後設置點擊事件像這樣=> $('tbody tr')。click(function(){...}); – 2011-04-10 20:46:11

+0

謝謝,但它不起作用。請問您.length == 1的含義是什麼?對不起還在學習;) – Jorge 2011-04-10 21:32:40

+0

這只是一種確保返回的結果集中只有一個隱藏的td的方法。如果您遇到問題,請在http://jsfiddle.net上發佈更強大的示例,以查看問題出在哪裏。 – 2011-04-10 22:00:34