Position table rows according to their dataset value

扶醉桌前 提交于 2021-01-29 12:27:57

问题


I am working on a sortable table. Every column has a button for giving each row a respective data-position value. For example, by clicking on a button for sorting rows in ascending order by alphabet I can assign datasets from 1 to n to each of those rows. When I click another button to sort by another parameter, I reassign those datasets.

The only issue now is that my rows stay at one place and don't change their positions. I assume I could do it with CSS positioning but not sure how.

Here is how I assign those datasets for existing table rows:

data.sort((a, b) => {
        if (a[dataId] === b[dataId]) {
            return 0;
        }
        return (a[dataId] > b[dataId]) ? -1 : 1;
    }).forEach((val, position) => {
        table.querySelector(`.${val.id}`).setAttribute('data-position', position + 1);
    });

回答1:


Here is how I've sorted tables.
I hope you can follow and see what it does and modify for your use.

// TableSort

function sortTable(tableElement, firstRow, colIndex, colType, reverseSort, toFixed2) {
  var rowColValue=[];
  for(var r=firstRow;r<tableElement.tBodies[0].rows.length;r++) {
    var rowId="row"+r.toString();
    tableElement.tBodies[0].rows[r].id=rowId;
    var cellValue=tableElement.tBodies[0].rows[r].cells[colIndex].innerText;
    if(colType=="Number") {
      if(cellValue=="—") cellValue="";
      else if(toFixed2) {
        if(cellValue.includes(".")) {
          if(cellValue.split(".")[1].length==1) tableElement.tBodies[0].rows[r].cells[colIndex].innerText+="0";
        } else {
          tableElement.tBodies[0].rows[r].cells[colIndex].innerText+=".00";
        };
      }
      cellValue=Number(cellValue.split(",").join(""));
    }
    rowColValue.push([rowId, cellValue]);
  }
  rowColValue.sort((a, b) => {
    var retVal=0;
    if(a[1]<b[1]) retVal=-1;
    else if(a[1]>b[1]) retVal=1;
    return retVal;
  });
  if(reverseSort) rowColValue.reverse();
  for(var rcv=0;rcv<rowColValue.length;rcv++) {
    tableElement.tBodies[0].rows[0].parentNode.appendChild(document.getElementById([rowColValue[rcv][0]]));
  }
}

Table element is the table id or document.getElementById("table-id-here").
First row: use 1 (if I remember correctly) if there is a heading, and 0 if there isn't.
Col index:...
Col type: if number, takes care of mixed 2, 2.0, 2.00...
reverseSort: true or false...
to fixed2: true or false for numbers from 7 to 7.00, 2.4 to 2.40, etc.
Basically, appending an existing row sends it to the bottom.



来源:https://stackoverflow.com/questions/62514962/position-table-rows-according-to-their-dataset-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!