单击标题时表顺序升序或降序

时间:2017-11-26 03:43:00

标签: javascript html sorting

我有一个由Javascript数组填充的HTML表格,而我正在尝试做的是,当点击“深度”时,它会将其排序为升序或降序。

这是我有一个函数的表:

var lakeData = [
 {
   "Month": "1959-01",
   "LakeErieLevels": 12.296
 },
 {
   "Month": "1959-02",
   "LakeErieLevels": 13.131
 },
 {
   "Month": "1959-03",
   "LakeErieLevels": 13.966
 },
 {
   "Month": "1959-04",
   "LakeErieLevels": 15.028
 },
 {
   "Month": "1959-05",
   "LakeErieLevels": 15.844
 },
 {
   "Month": "1959-06",
   "LakeErieLevels": 15.769
 },
 {
   "Month": "1959-07",
   "LakeErieLevels": 15.237
 },
 {
   "Month": "1959-08",
   "LakeErieLevels": 14.801
 },
 {
   "Month": "1959-09",
   "LakeErieLevels": 14.137
 },
 {
   "Month": "1959-10",
   "LakeErieLevels": 13.89
 },
 {
   "Month": "1959-11",
   "LakeErieLevels": 13.416
 },
 {
   "Month": "1959-12",
   "LakeErieLevels": 13.871
 }
];

var lakes = document.getElementById("lake");

lakeData.forEach(l => {
  var tr = document.createElement("tr");
  var d = tr.insertCell(0);
  d.innerHTML = l.Month;
  var de = tr.insertCell(1);
  de.innerHTML = l.LakeErieLevels;
  lakes.appendChild(tr);
});

这是HTML中的表格:

<table id="lake">
  <thead>
    <tr>
        <th>Date</th>
        <th>Depth</th>
    </tr>
</thead>
  <tbody>

  </tbody>
 </table>

同样,我一直在尝试做的是当点击“深度”标题时,它将按深度递增对表格进行排序,如果再次点击它,它将按降序排序。

1 个答案:

答案 0 :(得分:0)

以下是在点击th时对数据进行排序的方法:

//probably better to give your th element an id
//  and syle cursor:poiter
document.querySelectorAll("#lake th")[1].addEventListener(
  "click"
  ,(direction=>event=>{
    direction = direction * -1;
    lakeData.sort(
      (a,b)=>
        (a.LakeErieLevels>b.LakeErieLevels)
          ? direction
          : (a.LakeErieLevels<b.LakeErieLevels)
            ? direction * -1
            : 0
    );
    //redo your table with lakeData
  })(-1)
)