【问题标题】:Order table rows by two data attributes [duplicate]按两个数据属性排序表行[重复]
【发布时间】:2014-08-02 01:14:22
【问题描述】:

我有这张桌子:

<table id="tbl">
  <tr></tr>
  <tr data-pts="3" data-goals="3" data-points="3" data-newgoals="1" data-newpoints="3"></tr>
  <tr data-pts="2" data-goals="3" data-points="3" data-newgoals="1" data-newpoints="1"></tr>
  <tr data-pts="5" data-goals="3" data-points="3" data-newgoals="1" data-newpoints="3"></tr>
  <tr data-pts="4" data-goals="3" data-points="3" data-newgoals="1" data-newpoints="2"></tr>
</table>

我想通过两个数据属性对表格行进行排序:(points+newpoints)DESC,然后是(goals+newgoals)DESC(所以如果有两个表格行具有相同的points+newpoints,它将决定谁首先是目标+新目标)。

我找不到如何按两个属性对其进行排序。

【问题讨论】:

  • 指定一阶和二阶层次结构

标签: javascript jquery html


【解决方案1】:

这应该遍历元素并对数据点进行排序,我这样做很快,所以它可能无法 100% 工作,理想情况下,你希望将类似的东西包装到一个函数中,让你自己按多个属性排序性能,您不想直接在循环中编辑 DOM。

您应该使用 cloneNode 来制作您希望操作的 html 的副本,循环遍历它并对其进行排序,然后使用克隆调用 replaceChild 来更改 DOM。

[].forEach.call(document.querySelectorAll('[data-pts]'), function(e) {
    if (e.previousElementSibling && parseInt(e.getAttribute('data-pts')) < parseInt(e.previousElementSibling.getAttribute('data-pts'))) {
        e.parentElement.insertBefore(e, e.previousElementSibling)
    }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2013-03-19
    • 2020-09-22
    • 2014-02-28
    • 1970-01-01
    相关资源
    最近更新 更多