Using jquery. SortElements to achieve table sorting

  • 2020-03-30 02:48:39
  • OfStack

In the project to achieve the function of sorting table.

There are many solutions on the web, many of which are based on jQuery.

Jquery. Tablesorter, 17KB in size, but its home page has compatibility issues with ie10.
DataTables, size of 75KB, powerful, with paging, search and other functions.
There is also a plugin called sortElements, which is small, only 3KB, compatible, and has 818 stars on Github.

Finally, I choose to use sortElements. The implementation is simple:

1. Introduce the jQuery
 
<script type="text/javascript" src="jquery.js"></script> 

2. The introduction of sortElements. Js
 
<script type="text/javascript" src="jquery.sortElements.js"></script> 

3. The js code
 
$(document).ready(function(){ 
var table = $('#mytable');//The table id
$('#sort_header')//The headerid to sort
.each(function(){ 
var th = $(this), 
thIndex = th.index(), 
inverse = false; 

th.click(function(){ 
table.find('td').filter(function(){ 
return $(this).index() === thIndex; 
}).sortElements(function(a, b){ 
return $.text([a]) > $.text([b]) ? 
inverse ? -1 : 1 
: inverse ? 1 : -1; 
}, function(){ 
return this.parentNode; 
}); 
inverse = !inverse; 

}); 
}); 
}); 

4. The HTML code
 
<table id="mytable"> 
<tr> 
<th id="sort_header">Facility name</th> 
<th>Phone #</th> 
<th id="city_header">City</th> 
<th>Speciality</th> 
</tr> 
<tr> 
<td>CCC</td> 
<td>00001111</td> 
<td>Amsterdam</td> 
<td>GGG</td> 
</tr> 
... 
</table> 

Related articles: