如何将表行删除到其他行的末尾

时间:2017-07-18 12:00:58

标签: javascript mysql

我正在尝试将多个数据提取到表中,但是有一行是dubplicating是totalColumn,当​​我删除重复时,其余的都驻留在表的前面。我希望我把那行前面移到桌子的末尾

<table>
  <tbody>
    ...                
    <tr class="totalColumn">
      <td>Total</td>
      <td></td>
      <td></td>
      <td class="sumofamount">@FuelHistory.sumOfTwo(d.driver.Id) Litres</td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

用于删除行的Javascript:

$('.totalColumn').each(function() {
    var thisId = $(this).find('.sumofamount').text();
    var $rowsToGroup = $(this).nextAll('tr').filter(function() {
      return $(this).find('.sumofamount').text() === thisId;
    });

    $rowsToGroup.each(function() {
      $(this).remove();
    }
);

1 个答案:

答案 0 :(得分:1)

似乎你有重复的行,只想保留一个,并将那一行移到表的末尾。以下内容删除除 totalColumn 之外的所有行,然后将剩余的一行移至包含表格部分的末尾:

&#13;
&#13;
function fixTable(){
  // Get the total column rows
  var totalRows = document.querySelectorAll('.totalColumn');
  // Remove all but the first one
  for (var i=1, iLen=totalRows.length; i<iLen; i++) {
    totalRows[i].parentNode.removeChild(totalRows[i]);
  }
  //  Move first to end of containing table section
  totalRows[0].parentNode.appendChild(totalRows[0]);     
}
&#13;
<table>
  <tbody>
    <tr><td>foo<td>
    <tr><td>bar<td>
    <tr class="totalColumn"><td>Total</td><td>1,000</td></tr>
    <tr><td><td>
    <tr class="totalColumn"><td>Total</td><td>1,000</td></tr>
    <tr><td>fee<td>
    <tr><td>fumm<td>
  </tbody>
</table>
<button onclick="fixTable()">Fix table</button>
&#13;
&#13;
&#13;

您也可以使用 forEach 执行相同的操作,但上述内容与所有浏览器兼容,无需填充或转换回IE 8。

可以编写 fixTable 函数:

function fixTable(){
  [].forEach.call(document.querySelectorAll('.totalColumn'),
    (row, i) => row.parentNode[(i? 'remove' : 'append') + 'Child'](row)
  );
}

但我认为 for 循环更易于阅读,并且与旧浏览器更兼容(并且可能更快启动)。