Using a simple sorting example, we can understand the sorting rules with parameters in sort and the closure as parameters for calculation.
Below is a piece of HTML content:
<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml">
// $ Each is an iteration method. it traverses every element in the collection and uses it as a parameter to execute the closure operation function $ each (collection, closure) {var ret = []; // define the array for (VAR I = 0; I <collection. length; I ++) {// Add the result after the closure operation to the RET in the array set. push (closure (Collection [I]);} return ret;} // sort the table function sorttable (table, ID) {var rows = $ each (table. rows, function (x) {return X;}); If (ID = "ASC") // you can check whether the result is in ascending order {
// Sorting method with closure parameters, which can control the ascending or descending order. Rows. sort (function (a, B) {if (. childnodes [0]. innertext-0> B. childnodes [0]. innertext-0) {return 1;} else return-1;});} else if (ID = "DESC") {rows. sort (function (a, B) {if (. childnodes [0]. innertext-0> B. childnodes [0]. innertext-0) {return-1;} elsereturn 1 ;}) ;}// Add the sorted rows to the table $ each (rows, function (x) {X. parentelement. appendchild (x); Return X;}) ;}</SCRIPT>
The corresponding output graph:
After you click Sort by ASC, it is displayed as follows:
Click sort by DESC and the output is: