jQuery表以前缀和日期作为字符串排序

时间:2018-08-08 00:15:16

标签: javascript jquery

以Nick Grealy在这里的答案为基础:Sorting HTML table with JavaScript,我添加了大多数sort criteria典型的其他tables

为帮助人们寻找一种整体处理解决方案,对prefixesdelimitersdate as a string进行分类的最佳方法是什么?

另外,应该使用RegEx来识别用于thousands的分隔符吗?

const getCellValue = (tr, idx) =>
  tr.children[idx].innerText || tr.children[idx].textContent;

const comparer = (idx, asc) => (a, b) =>
  ((v1, v2) =>
    v1 !== "" && v2 !== "" && !isNaN(v1) && !isNaN(v2) ?
    v1 - v2 :
    v1.toString().localeCompare(v2))(
    getCellValue(asc ? a : b, idx),
    getCellValue(asc ? b : a, idx)
  );

// do the work...
document.querySelectorAll("th").forEach(th =>
  th.addEventListener("click", () => {
    const table = th.closest("table");
    Array.from(table.querySelectorAll("tr:nth-child(n+2)"))
      .sort(
        comparer(
          Array.from(th.parentNode.children).indexOf(th),
          (this.asc = !this.asc)
        )
      )
      .forEach(tr => table.appendChild(tr));
  })
);
th {
  cursor: pointer
}

td {
  border: 1px solid;
  padding: 10px;
}
<table>
  <tr>
    <th>Country</th>
    <th>Date</th>
    <th>Date (text)</th>
    <th>Price</th>
  </tr>
  <tr>
    <td>France</td>
    <td>2018-04-03</td>
    <td>Apr 03, 2018 10:30PM</td>
    <td>$2500</td>
  </tr>
  <tr>
    <td>spain</td>
    <td>2018-03-05</td>
    <td>Mar 05, 2018 12:19PM</td>
    <td>$11,000</td>
  </tr>
  <tr>
    <td>Lebanon</td>
    <td>2018-03-05</td>
    <td>Mar 05, 2018 04:30AM</td>
    <td>$980</td>
  </tr>
  <tr>
    <td>Argentina</td>
    <td>2018-09-13</td>
    <td>Sept 13, 2018 01:50AM</td>
    <td>$8100</td>
  </tr>
  <tr>
    <td>USA</td>
    <td>2017-012-17</td>
    <td>Dec 17, 2017 11:30AM</td>
    <td>$6000</td>
  </tr>
</table>

0 个答案:

没有答案