将列(包括thead和td)移到新位置

时间:2019-05-13 07:13:20

标签: javascript jquery html

我有一个这样的表,第3列是复选框的列

header1   header2     header3
 cell1     cell2     checkbox3
 cell1     cell2     checkbox3
 cell1     cell2     checkbox3

我想像这样将第3列移到第1列之后

header1     header3      header2
 cell1     checkbox3      cell2
 cell1     checkbox3      cell2
 cell1     checkbox3      cell2

这是我到目前为止尝试过的:

$('thead tr:nth-child(2)').insertAfter('thead tr:nth-child(0)');
$('tbody tr:nth-child(2)').insertAfter('tbody tr:nth-child(0)');

表格代码:

<table>
  <thead>
   <tr>
    <th>header1</th>
    <th>header2</th>
    <th>header3</th>
   </tr>
  </thead>
  <tbody>
   <tr>
    <td>cell1</td>
    <td>cell2</td>
    <td><input type="checkbox" />checkbox3</td>
   </tr>
   <tr>
    <td>cell1</td>
    <td>cell2</td>
    <td><input type="checkbox" />checkbox3</td>
   </tr>
   <tr>
    <td>cell1</td>
    <td>cell2</td>
    <td><input type="checkbox" />checkbox3</td>
   </tr>
  </tbody>
</table>

但是没有用,我能解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

怎么样呢?

function swapColumns (table, sourceCol, destCol) {
    let rows = $("tr", table);  // get rows in table
    let cols;   // declare cols variable
    rows.each(function() {
        cols = $(this).children("th, td");  // cols include th and td
        cols.eq(sourceCol).detach().insertBefore(cols.eq(destCol)); // swap 'em
    });
}

let table = $("#tableSelector");
swapColumns(table);