如何在同一行中显示具有其id的两个tr's

How to display two tr's with its id in the same row by its id

本文关键字:两个 id tr 一行 显示      更新时间:2023-09-26

我有一个带有tr标签的表。我想在它的类旁边并排显示两个tr标记。如何使用jquery来实现呢?

<table>
   <tr class='1'>
     <td>First</td>
   </tr>
   <tr class='1'>
      <td>second</td>
   </tr>
   <tr class='2'>
       <td>third</td>
   </tr>
   <tr class='3'>
       <td>fourth</td>
   </tr>
   <tr class='3'>
       <td>fifth</td>
   </tr>  
</table>

然后在输出中我想显示

 First     Second
 Third
 Fourth    Fifth

我想动态地设置这些,我如何使用jquery或javascript做到这一点。我想使用为tr标签声明的类。我知道我想用<td>标签。

我想到的第一种方法是:

var $tds = $("td");      // get all the tds
[].reverse.call($tds);   // reverse the order so we can easily loop backwards
$tds.each(function() {
    var $parentRow = $(this).parent(),
        // find the first row with the same class that isn't this row
        $firstTrSameClass = $("tr").filter("." +$parentRow.attr("class"))
                                   .not($parentRow).first();
    if ($firstTrSameClass.length > 0) { // if there is such a row
        $firstTrSameClass.append(this); // move the td
        $parentRow.remove();            // delete the original row
    }   
});

演示:http://jsfiddle.net/pgcdq/

我真的看不到这里的用例,但我想最简单的是创建新行并将单元格移动到它们。你可以在这里找到有关移动元素的信息:如何将一个元素移动到另一个元素中?