【问题标题】:Move column (including thead and td) to a new position [duplicate]将列(包括thead和td)移动到新位置[重复]
【发布时间】:2019-05-13 07:13:20
【问题描述】:

我有一个这样的表,第 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>

但它不起作用,有什么想法我可以解决这个问题吗?

【问题讨论】:

  • 如果你说你想切换columns,你为什么还要在桌子上尝试rows……

标签: javascript jquery html


【解决方案1】:

这样的事情怎么样:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-13
  • 2012-09-28
  • 1970-01-01
  • 1970-01-01
  • 2011-12-15
相关资源
最近更新 更多