开发者

Retrieving td hidden cell using jQuery

I have the following table:

<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> 

and then this jQuery code to hide the id column:

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

I need to get the id cell hidden value when开发者_运维技巧 I click on any row but I cannot find the right selector. Any help will be appreciated. Thanx.


Try this:

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

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

UPDATE

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

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

If you have many columns and want to select the first one, you can use :first. Remember, this will add click event for all your rows in your table. I suppose you're only intrested in the rows within your tbody, which your example doesn't have. So I would do this instead:

<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> 

and then set click events for tbody rows

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

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

Hope that helps!


I am going assume you me the .text() of the <td class="hidden">87</td> or 87

You can register a click handler on the <tr/> and then find your <td/>

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

Edit

A slightly better option might be to use .filter() so you only register event handlers that have a child <td class="hidden"/>

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜