javascript - jQuery 按数据位置或 id 对表 tr 进行排序

标签 javascript jquery html-table

我有一些带有这些 html 结构的动态生成的表

<table class="deliver">
  <tbody class="tbody">
    <tr id="10" data-position="10">
      <td>Title</td>
    </tr>
    <tr id="10" data-position="10">
      <td>Content</td>
    </tr>
    <tr id="23" data-position="23">
      <td>Title</td>
    </tr>
    <tr id="23" data-position="23">
      <td>Content</td>
    </tr>
  </tbody>
</table>

<table class="deliver">
  <tbody class="tbody">
    <tr id="3" data-position="3">
      <td>Title</td>
    </tr>
    <tr id="3" data-position="3">
      <td>Content</td>
    </tr>
    <tr id="2" data-position="2">
      <td>Title</td>
    </tr>
    <tr id="2" data-position="2">
      <td>Content</td>
    </tr>
    <tr id="2" data-position="2">
      <td>Extra content (sometimes)</td>
    </tr>
  </tbody>
</table>

每个都有一个tbodytr。 id 和数据位置范围在 1 到 23 之间。我需要某种排序方法来保留标题内容对,但在每个表中对 id 进行升序排序。我发现thisthis教程,但在我的情况下不起作用(什么也没有发生)。

我的代码片段如下所示

$(".tbody").each(function(){
    $(this).html($(this).children('tr').sort(function(a, b){
        return ($(b).data('position')) < ($(a).data('position')) ? 1 : -1;
    }));
});

最佳答案

您可以使用 Array.prototype.sort用于非平凡排序的回调。

下面的演示循环遍历所有表并排序 <tr> s 同时尊重 data-position属性升序(1,2,3…)将标题保留在内容之前

// Loop over all tables
$('table').each(function() {
  // Retrieve references to current table TR elements
  let collection = Array.from(this.querySelectorAll('tr'))
      .sort(function(x, y) {
        let posX = +x.dataset.position
            ,posY = +y.dataset.position;
        // Behavior when items haven't the same position
        if (posX != posY) {
            return posX > posY ? 1 : -1;
        }
        // When items have the same position
        return x.textContent.toLowerCase().trim() == 'Title' ? 1 : -1;
      })
  ;

  // Finally move items into the container using the computed order
  collection.forEach(element => {
    this.querySelector('.tbody').append(element);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="deliver">
  <tbody class="tbody">
    <tr data-position="23">
      <td>Title 23</td>
    </tr>
    <tr data-position="23">
      <td>Content 23</td>
    </tr>
    <tr data-position="10">
      <td>Title 10</td>
    </tr>
    <tr data-position="10">
      <td>Content 10</td>
    </tr>
    <tr data-position="12">
      <td>Title 12</td>
    </tr>
    <tr data-position="12">
      <td>Content 12</td>
    </tr>
  </tbody>
</table>

关于javascript - jQuery 按数据位置或 id 对表 tr 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49412661/

相关文章:

javascript - 使用 Parse.com 查询制作新闻源

javascript - 确保从未使用表单输入字段开头的 =

html - 使用 CSS 定位数字的 html 表格日历

html - 第一列最小宽度的响应表;第二列拉伸(stretch);第三列总是在最后;我怎样才能做到这一点?

javascript - 如何解决基本标签的问题?

javascript - 正则表达式适用于 JavaScript,但不适用于 PHP

jquery - Select2初始化回调

javascript - 如何抓取有事件的链接内的数据?

javascript - 如何在 jquery 中将 json 数据转换为 html 表?

javascript - jQuery 如何从行中获取数据