I\'m working on project which don\'t use jQuery but only JavaScript and we have a need to sort alphabetically ascending a table values (without any external library).
<
I'm sharing my own solution here. If you have any remark or suggestions, please share.
I'm updating my solution by adding an inverse order feature:
var sortableTable = {
/**
* The table to sort
*/
table: null,
getTable: function(){
return this.table;
},
setTable: function(table){
this.table = table;
},
/**
* The column used for sorting
*/
element: null,
getElement: function(){
return this.element;
},
setElement: function(element){
this.element = element;
},
/**
* When ooderDirection is 1 => Ascending order
* When ooderDirection is -1 => Descending order
*/
orderDirection: 1,
getOrderDirection: function(){
return this.orderDirection;
},
setOrderDirection: function(orderDirection){
this.orderDirection = orderDirection;
},
/**
* Get table rows elements
*/
getRows: function(){
var rows = [];
if(null !== this.getTable()){
var allRows = this.getTable().rows;
/*
When I returned allRows directly,
in the sort function when I do: rows.sort();
it display an error: Uncaught TypeError: rows.sort is not a function
So I'm converting this object to an array
*/
var arrayRows = [];
//allRows contains all rows with elements,
//so I'm removing th elements (index 0)
for(let i=1 ; i New sort based on '" + this.innerText + "' <------");
// Set the current clicked element
sortableTable.setElement(this);
//Inverse the order
sortableTable.setOrderDirection( sortableTable.getOrderDirection() * -1 );
//Do the sort and refresh table result
sortableTable.sort(this.cellIndex);
});
};
table{
font-size: 16px;
border-collapse: collapse;
border-spacing: 0;
width: 100%;
}
table th{
padding-top: 11px;
padding-bottom: 11px;
background-color: #6295a5;
color: white;
}
table td{
border: 1px solid #ffffd;
text-align: left;
padding: 8px;
}
table tr:nth-child(even) {
background-color: #f2f2f2;
}
table th{
cursor: pointer;
}
table th:hover{
color: #dea82e;
background-color: #37545d;
}
Names
Functions
Emails
Tel
xMxxx
Physicists
xmxxx@domain.com
00 55 99 99 99
xJxxx
Air Traffic Controllers
xjxxx@domain.com
00 22 99 99 99
xExxx
Engineer
xexxx@domain.com
00 33 99 99 99
xAxxx
Mechanical engineer
xaxxx@domain.com
00 11 99 99 99
xZxxx
Doctor
xzxxx@domain.com
00 44 99 99 99
xPxxx
Professor
xpxxx@domain.com
00 66 99 99 99
讨论(0)
- 热议问题