【问题标题】:How can i get all TD data upon clicking on a TR with Jquery如何在使用 Jquery 单击 TR 时获取所有 TD 数据
【发布时间】:2011-02-24 06:53:24
【问题描述】:

我有一个包含多行的表,我想在单击特定行后获取所有 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、name、gender。

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

谢谢

【问题讨论】:

    标签: jquery datatable


    【解决方案1】:

    这里是解决方案。你可以试试 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);
        });
    
    });
    

    【讨论】:

      【解决方案2】:

      更新:

      单独获取:

      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

      【讨论】:

      • @谢谢。但我想要单独的字段而不是整个数据。
      • @KillerFish:好的,请查看我的答案更新以分别获取它们:)
      【解决方案3】:
      $("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();
      });
      

      【讨论】:

        【解决方案4】:

        你可以使用

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

        【讨论】:

          【解决方案5】:

          我遇到了同样的问题,最后用这个代码从表中获取所有 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);
           });
           });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-05-22
            • 2012-03-06
            • 2020-10-14
            • 1970-01-01
            • 2018-10-26
            • 1970-01-01
            相关资源
            最近更新 更多