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

标签 javascript mysql

我正在尝试将多个数据获取到表中,但是有一行是重复的,即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();
    }
);

最佳答案

您似乎有重复的行,并且只想保留一行,然后将该行移动到表的末尾。以下代码删除 totalColumn 行中除一行之外的所有行,然后将剩余行移动到包含表部分的末尾:

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

您也可以使用 forEach 来做同样的事情,但上面的内容与所有浏览器兼容,直到 IE 8,无需填充或转译。

fixTable函数可以这样写:

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

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

关于javascript - 如何将表行删除到其他行的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45166207/

相关文章:

javascript - JavaScript 中的方法对象

javascript - onChange 事件未在 Chrome 中的文本框上触发

mysql - 删除 MySQL 中的非字母数字

php - 为什么我的 PHP 登录脚本不起作用?

php - MailTo 中的数百封电子邮件 - Outlook/Windows?

javascript - backbone.js 更新模型默认值

javascript - YouTube视频更改上的Javascript

javascript - 如何删除函数及其中的所有对象/处理程序?

mysql - 在 1 个 mySQL 查询中使用 2 个 INNER JOINS 时出现问题

php - 我可以在 PHP 中混合使用 MySQL API 吗?