如何在点击带有Jquery的TR时获取所有TD数据

时间:2011-02-24 06:53:25

标签: jquery datatable

我有一个包含多行的表格,我希望在点击特定的ROW后获得所有的TD数据。

我的表是

<table>
 <tr class="person">
   <td class="id">1900</td>
   <td class="name">John</td>
   <td class="gender">Male</td>
 </tr>

 <tr class="person">
   <td class="id">2000</td>
   <td class="name">Pitt</td>
   <td class="gender">Female</td>
 </tr>
</table>

如何使用Jquery点击Row后获取ID,名称,性别。

Ex: If i click on John Row i should get 1900, John, Male and same for Pitt also

谢谢

5 个答案:

答案 0 :(得分:6)

这是解决方案。您可以尝试使用find()方法而不是children()

$(function(){
    $('.person').click(function(){
        var id = $(this).children('.id').text();
        var name= $(this).children('.name').text();
        var gender = $(this).children('.gender').text();

        alert('Selected ID: ' + id + ', Name: ' + name + ', Gender: ' + gender);
    });

});

答案 1 :(得分:3)

<强>更新

单独获取它们:

var arr = [];
$('#tableID > tbody > tr').click(function(){
  arr = $(this).find('td').map(function(){
     return this.innerHTML;
  }).get();

  arr = arr.split(',');
  var id = arr[0];
  var name = arr[1];
  var gender = arr[2];
});

你可以这样做:

var arr = [];
$('#tableID > tbody > tr').click(function(){
  arr = $(this).find('td').map(function(){
     return this.innerHTML;
  }).get();

  alert(arr);
});

Check out the DEMO

答案 2 :(得分:1)

$("tr").bind("click", function(e){
 var id = $(this).find("td.id").text();
 var name = $(this).find("td.name").text();
 var gender = $(this).find("td.gender").text();
});

答案 3 :(得分:0)

你可以使用

$(function(){
    $('.person>td').click(function(){
        console.log($(this).parent().children().text());
    })

});

答案 4 :(得分:0)

我遇到了同样的问题,最后使用此代码解决了从表中获取所有tr数据的问题:

$('.tb_add').click(function ()
{
  var table = $("table tbody");
  table.find('tr').each(function (i) {
        r1 = $(this).find('td').eq(0).text();
        r2 = $(this).find('td').eq(1).text();
        alert(r1+" "+r2);
 });
 });