简体   繁体   中英

Client side sorting with html and Javascript

How can I make a html table which the user can sort using the column headers to sort on the client side? I can load all rows' html data into a Javascript array and use dom to add a table to a content div but is it the right way? If you list major methods, I can find my way from there so, I'm not asking for code.

No need to reinvent the wheel in case you utilise a JS Framework already, but here are quite some nice solutions:

TableSort - http://www.frequency-decoder.com/demo/table-sort-revisited/

JQuery tablesorter - http://tablesorter.com/docs/#Demo

GridView3 - http://dev.sencha.com/playpen/ext-2.0/examples/grid/grid3.html

Stuart Langridge's Script - http://yoast.com/articles/sortable-table/

Mootools Mootable - http://joomlicious.com/mootable/

tablesorter很好,但是您希望内置一些过滤功能,并且已经得到广泛使用和支持,请尝试http://datatables.net/

Every tablesorter works like this:

  1. get the table.tbody.rows in an array
  2. sort that array using a custom compare function
  3. append the rows to the table body in the correct order

It is usually be a bit faster if you precompute the values-to-compare (instead of accessing the DOM elements on every comparison), the array would then contain objects that have the value in one slot and the table row element in the other.

If you have an array, then calling sort() is probably your best bet:

function sortArray(a, b){
  //could also say return a-b instead of the blown out if...else construct
  if(a.Age===b.Age) { return 0; }
  else if (a.Age < b.Age) { return -1; }
  else { return 1; }
}

var rows = [{Name: 'Amy', Age: 10}, {Name: 'Bob', Age: 20}];
var sortedArray = rows.sort(sortArray);

As the other answers have stated, you can also use a plug-in. DataTables is a good one that I've used in the past.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM