JavaScript multiple data types table sorting code Analysis _javascript Tips

Source: Internet
Author: User
Tags abs date1 first row
Chinese character sorting,
Mixed sorting in Chinese and English,
Data size sorting,
File type sort (suffix name sort)
Date Time sorting,
Price sorting,
Chinese mixed digit sorting;
How to: The document is loaded with the new Tablelistsort (arguments,arguments).

Accept two parameters: The first argument is required, can be a string ID, or a Table object; the Second optional parameter, this parameter is an object, {data:index,filetype:index,fn:function () {}}; object has three optional properties. The first and second data types that are sorted by extension, and the third parameter is the function that needs to be sorted, and if the table data contains data types that need to be sorted, such as 1KB 1MB 1GB, you can {Data:index};index the subscript value of a column that you want to sort for the table. Count from 0, such as the second column in the table, 1KB MB of data type, {data:2}; the second property {Filetype:index} of the object, which is sorted as a file type, such as a suffix named Xml,jpg,exe. Index is also the subscript value of the column.

The third optional property of the object is a function {fn:function () {executes code}} that needs to be executed after sorting.

The elements that must be in the HTML code are: The table element, and the first row of the table element must use the THEAD element to contain elements in tr,tr that must contain clickable sorting th;thead the next sibling element must be in Tbody,tbody to contain tr. The sorted data is included with TD, and table can contain caption and tfoot.

April 11, Update: Adds a label icon in ascending order after sorting.
Custom Add Class If you do not want to add this property you can not set, the mouse style mymickey in the script added without the need for CSS.
Table. Index is the coordinate value that was last sorted; index initialized to null;
The Fn:fini function is only a function that needs to be executed after sorting, and even if it is not, it can be sorted, passing a sort of function that needs to be executed just to add sort down and up logo icons.

The following source code:
Copy Code code as follows:

Window.onload=function () {
function fini (num) {
Table.th[num].classname=
table.th[num].classname== ' Selectup '?
' Selectdown ': ' Selectup ';//Toggle indicator icon

each (table). Row,function (o) {//highlight Highlight the currently sorted column
O.cells[num].classname= ' highlight ';
if (table. Index!=null&&table. Index!=num) {
O.cells[table. Index].classname= ';
}
});
if (table. Index!=null&&table. Index!=num) {//other clicked original cancelled icon
Table.th[table. Index].classname= ';
}
}

var table=new tablelistsort ($ (' TB '), {Data:8,filetype:9,fn:fini})//document load new pass parameter
}

Copy Code code as follows:

var class={
Create:function () {
return function () {
This.init.apply (this,arguments)
}
}
}
function each (O,FN) {
for (Var j=0,len=o.length;j<len;j++) {
FN (O[J],J)
}
}

Function.prototype.bind=function () {
var method=this;
var args=array.prototype.slice.call (arguments);
var object=args.shift ();
return function () {
Return method.apply (Object,args.concat (Array.prototype.slice.call (arguments))
}
}
function $ (elem,elem2) {
var arr=[];
typeof elem== ' string ' Arr.push (document.getElementById (elem)): Arr.push (Elem);
Elem2&&arr.push (Arr[0].getelementsbytagname (ELEM2));
(arr.length>1) && (typeof elem== ' object ') && (Arr.shift ());
return arr.length!=2?arr[0]:arr[1];
}

var tablelistsort=class.create ()
tablelistsort.prototype={
Init:function (tables,options) {
this.table=$ (tables);//Find TABLE element
this.th=$ ($ (this.table, ' thead ') [0], ' th ');/find th element
this.tbody=$ (this.table, ' tbody ') [0];//find TBODY Element
This. row=$ (This.tbody, ' tr '); Find the TR Element
This.rowarr=[];//tr into this array
This. Index=null;
this.options=options| | {};
this.finish=this.options.fn| | function () {};
This.dataindex=math.abs (this.options.data) | | null;//provides coordinates for the comparison data type.
This.file=math.abs (this.options.fileType) | | NULL;//provides the need to compare file type coordinates
Each (this. Row,function (o) {this.rowArr.push (O)}.bind (this));//Load a TR object list into an array
for (Var i=0;this.th.length>i;i++) {
This.th[i].onclick=this. Sort.bind (this,i)//use bind to keep a subscript value (variable) indirectly, passing past
this.th[i].style.cursor= ' pointer ';
}
this.re=/([-]{0,1}[0-9.] {1,}) /g;//Replacement Regular Expression
This.dataindex&&subdata (this. Row,this.dataindex,this. Row.length);
},

Sort:function (num) {
var date1=new Date (). GetTime ()//test for sort time if you want to test the sort time, please comment and remove
The other was clicked and the original was canceled to indicate the icon
(This. Index!=null&&this. Index!=num) &&this.th[this. Index].setattribute (' sorted ', ');
This.th[num].getattribute (' sorted ')!= ' Ed '?
This.rowArr.sort (This.naturalSort.bind (This,num)): This.rowArr.reverse ();
If the current object is clicked, use the reverse () column directly to reverse the order, otherwise sort, because the predefined sort () method is used, so if the function that performs the sort
If you know the subscript value of the column you want to sort, bind () passes NUM past, this to invoke;
var frag=document.createdocumentfragment ();//Create Document fragmentation
Each (This.rowarr,function (o) {frag.appendchild (O)});//Insert the sorted array into the document fragment
This.tbody.appendChild (Frag);//Fragment Insert Node
This.th[num].setattribute (' sorted ', ' Ed ');
$ (' spans '). Innerhtml= (New Date (). GetTime ())-date1;//test for sort time if you want to test the sort time, please comment and remove
This.finish (num);//The function that is performed after sorting
This. index=num;//The coordinate value that is ordered
},
Naturalsort:function (Num,a, b) {
Judge whether the data is sorted if it is. Find attributes
var a=this.dataindex!=num?a.cells[num].innerhtml:a.cells[num].getattribute (' Data '),
B=this.dataindex!=num?b.cells[num].innerhtml:b.cells[num].getattribute (' data ');
Num is passed by the bind method to find the contents of the cell that needs to be sorted
var x = a.tostring (). toLowerCase () | | ", y = b.tostring (). toLowerCase () | | '',
NC = String.fromCharCode (0),
XN = X.replace (this.re, NC + ' "+ NC). Split (NC),//split string into groups
YN = Y.replace (this.re, NC + ' $ ' + NC). Split (NC),
XD = (new date (x)). GetTime (), YD = (new date (y)). GetTime ()
XN = This.file!=num?xn:xn.reverse (),//If there is filetype, reverse order
YN = This.file!=num?yn:yn.reverse ()

if (XD && yD && XD < YD)
return-1;
else if (XD && yD && xD > YD)
return 1;
For (var cloc=0, nums = Math.max (Xn.length, yn.length); CLoc < nums; cloc++)
if ((parsefloat (xn[cloc) | | xn[cloc]) < (parsefloat (yn[cloc)) | | yn[cloc])
cannot be converted to Floatnumber for direct alphabetic comparisons, such as ' A ' < ' B ' print//true
return-1;
else if ((parsefloat (xn[cloc) | | xn[cloc]) > (parsefloat (yn[cloc) | | yn[cloc])
return 1;
return 0;
}

}
function Subdata (O,i,len) {//If there is a data size sorted to TD to add a custom attribute to data//is also possible to judge the//mymickey is not here to write regular
for (Var j=0;len>j;j++) {
if (o[j].cells[i].innerhtml.substring (o[j].cells[i].innerhtml.lastindexof (' KB ')). toLowerCase () = = ' kb ') {
O[j].cells[i].setattribute (' Data ', parsefloat (o[j].cells[i].innerhtml) *1024);
}
if (o[j].cells[i].innerhtml.substring (O[j].cells[i].innerhtml.lastindexof (' MB ')). toLowerCase () = = ' mb ') {
O[j].cells[i].setattribute (' Data ', parsefloat (o[j].cells[i].innerhtml) *1000000);
}
else if (o[j].cells[i].innerhtml.substring (O[j].cells[i].innerhtml.lastindexof (' GB ')). toLowerCase () = = ' GB ') {
O[j].cells[i].setattribute (' Data ', parsefloat (o[j].cells[i].innerhtml) *1000000000);
}
}
}

Copy Code code as follows:

TABLE#TB {
Text-align:center;
border:1px #ccc Solid;
Border-collapse:collapse;
font-size:12px;
Font-family:arial, Helvetica, Sans-serif;
Color: #666;
width:900px;
Background:url (room-bg.gif) 0-13px repeat-x;
}
TABLE#TB TD {
Border-bottom: #ccc 1px solid;
Padding:.3em 0 3em 0;
}

#tb th {
height:30px;
Color: #009;
padding-right:16px;
}
#tb thead tr{

}

#tb td.highlight{color: #000;}
#tb Th.selectup {
Background:url (up1.png) No-repeat Right center transparent;

}
#tb Th.selectdown {
Background:url (down1.png) No-repeat Right center transparent;
}
#tb tfoot{
Font-weight:bold;
Color: #06F;
Background:url (room-bg.gif) 0-13px repeat-x;
}

Package Download http://www.jb51.net/jiaoben/32017.html
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.