JavaScript对表格或元素按文本,数字或日期排序的方法
本文实例讲述了JavaScript对表格或元素按文本,数字或日期排序的方法。分享给大家供大家参考。具体实现方法如下:
//Sortingtablecolumnscorrectlybytext,numberordate.Thereareother
//versions,plugins,etc.,forthisbuttheyeitherarerestrictedtospecific
//dateformats,orrequireEVERYrow-elementtobegivenasortattribute;mine
//canhandlemanydifferentdateandnumberformats,andevenallowsforspecific
//cellsthatmaynotconformtotheoveralldate/numberformatforthatcolumn.
//Myversionalsoenablessortingofelementhierarchies:suchasaDIVcontaining
//P-paragraphsandSPANs-thiscouldevenbeanimage-gallerycontainingprices
//ordateswithinspans.Veryefficientaswell!!
//Example:andrew.dx.am/sortgallerydel.html
//AddSortToTables();willmakethetableheadersclickable,tosortcolumnsin
//ascendingordescendingorder,foranytableswithclass="sortIt".
//SortTable(tbl,col);willsortthetable(tblisanidortableobject)by
//thesuppliedcolumnindex(indexedfrom0)inascendingordescendingorder.
//AddSortByDate(tbl,col,dateMask);enablessortingofacolumnbydate,
//specifiedbyadate-masksuchas'dd-mmm-yy'.
//AddSortByNumber(tbl,col);enablessortingofacolumnbynumber.Thisassumesa
//period.asthedecimalseparator(ifpresent);itignoresanyothernon-numeric
//characters.
//SortElements(parentEl,childTag,colTag,colIndex);willsort(non-table)
//elementsinascendingordescendingorder.Forexample,anULcontainingLIs
//andSPANs.colIndexspecifieswhichspantosort;theremaybemorethanonein
//theLI(0indexed).
//Example:SortElements('divid','p','span',2);
//3rdspanwithineachparagraph.
//
//AddSortByDate2(parentEl,childTag,colTag,colIndex,dateMask);and
//AddSortByNumber2(parentEl,childTag,colTag,colIndex)
//providethesamefeature-setasAddSortByDateandAddSortByNumberdoes
//fortables,butforelementhierarchies.
//Iftherearedatesornumbersinacolumn(orelement)whichdon'tmeetthe
//date-maskornumberformattingnecessarytosortcorrectly,thentheseindividual
//elementscanbegiventheattribute"sort"andtheywillstillsortcorrectly!
//Forexample,withadatecolumn<tdsort="2012/12/20">willstillsorta
//cellcorrectly.(Thisformat'YYYY/MM/DD'willbeconvertedintoaDate()object.)
varMonthNames=["January","February","March","April","May","June","July",
"August","September","October","November","December"];
varDayNames=["Sunday","Monday","Tueday","Wednesday","Thursday",
"Friday","Saturday"];
varShortMths=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug",
"Sep","Oct","Nov","Dec"];
varShortDays=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
varAddEvent=function(elem,eventType,func){
//Helperfunction.
if(elem.addEventListener)
AddEvent=function(elem,eventType,func){
elem.addEventListener(eventType,func,false);
};
elseif(elem.attachEvent)
AddEvent=function(elem,eventType,func){
elem.attachEvent('on'+eventType,func);
};
else
AddEvent=function(elem,eventType,func){
elem['on'+eventType]=func;
};
AddEvent(elem,eventType,func);
};
//Sortmethods/algorithmsattributed:
varSortTable=function(tbl,col){
//couldbecalleddirectly
SortElements(tbl,'tr','td',col);
};
varSortElements=function(parentEl,childTag,colTag,colIndex){
//exampleuse:SortElements('table1','tr','td',2)
//orSortElements('list1','li')
//orSortElements('divName','p','span',3)
vari,j,cTags={},startAt=0,childLen,aChild,elem,
sortBy,content,elems=[],sortedLen,frag,hdrsLen,hdr;
varparent=(typeofparentEl==='string')?
document.getElementById(parentEl):parentEl;
varAscText=function(a,b){//sort()by.dataastext
varx=a.data,y=b.data,
xNum=parseFloat(x),yNum=parseFloat(y);
//checkifeachbeginwithanumber..
if(!isNaN(xNum)&&!isNaN(yNum)&&(xNum-yNum))
returnxNum-yNum;
return((x<y)?-1:((x>y)?1:0));
};
varDescText=function(a,b){//sort()by.data
varx=a.data,y=b.data,
xNum=parseFloat(x),yNum=parseFloat(y);
//checkifeachbeginwithanumber..
if(!isNaN(xNum)&&!isNaN(yNum)&&(yNum-xNum))
returnyNum-xNum;
return((x>y)?-1:((x<y)?1:0));
};
varAscNum=function(a,b){//usedwithdatesaswell
returna.data-b.data;
};
varDescNum=function(a,b){
returnb.data-a.data;
};
if(parent.nodeName.toLowerCase()=='table'){
if(childTag=='tr'){
sortBy=parent.rows[0].cells[colIndex].sortBy||'text';
}
parent=parent.tBodies[0]||parent;
if(parent.rows[0].cells[0].nodeName.toLowerCase()=='th'){
startAt=1;
}
}
cTags=parent.getElementsByTagName(childTag);
if(typeofcolIndex=='undefined'){
sortBy='text';//sortsimplelistsorparagraphsastext
}
for(i=startAt,childLen=cTags.length;i<childLen;i++){
//..goforwardexaminingeachchild
aChild=cTags[i];
elem=(colTag)?aChild.getElementsByTagName(colTag)[colIndex]:aChild;
if(elem){
if(!sortBy){//sortingnon-tablecolumns..
sortBy=(typeofelem.numberValue!='undefined')?'number':
((typeofelem.dateValue!='undefined')?'date':'text');
}
switch(sortBy){
//Youcansupply'sort'attributestoenablesortingofnumbers,etc.
//Forexample,<tdsort='2011/02/12'>foradate.
case'text':
content=(elem.getAttribute('sort')||
elem.firstChild.nodeValue).toLowerCase();
break;
case'number':
content=elem.numberValue;
break;
case'date':
content=elem.dateValue;
break;
default:
content=(elem.getAttribute('sort')||
elem.firstChild.nodeValue).toLowerCase();
break;
}
j=elems.length;
if(!aChild.id)
aChild.id='tempSortID'+j;
elems[j]={data:content,tempID:aChild.id};
}
}
//Thefollowingwilldetermineifthetable/etchasalreadybeensorted
//bythesamecolumnortag.Ifso,itwillsortinascendingordescending
//order.Itcreatescustomelementpropertiestotheparentelementto
//remembertheprevioussortdetails.
if(typeofcolIndex=='undefined')colIndex=0;
if(parent.prevTag&&parent.prevTag==((typeofcolTag=='undefined')?
childTag:colTag)){
if(parent.prevCol==colIndex){
//sortingbythesamecolumnaspreviously
parent.prevSort=(parent.prevSort=='asc')?'desc':'asc';
}else{//sortingbyanyothercolumn
parent.prevCol=colIndex;
parent.prevSort='asc';
}
}else{
//sortingforthe1sttimeorbyadifferenttag
parent.prevTag=((typeofcolTag=='undefined')?childTag:colTag);
parent.prevCol=colIndex;
parent.prevSort='asc';
}
if(parent.prevSort==='desc'){
//'desc'WILLBEtheprevioussortorder..
switch(sortBy){
case'text':elems.sort(DescText);break;
case'number':elems.sort(DescNum);break;
case'date':elems.sort(DescNum);break;
default:elems.sort(DescText);break;
}
}else{
switch(sortBy){
case'text':elems.sort(AscText);break;
case'number':elems.sort(AscNum);break;
case'date':elems.sort(AscNum);break;
default:elems.sort(AscText);break;
}
}
frag=document.createDocumentFragment();
for(i=0,sortedLen=elems.length;i<sortedLen;i++){
elem=document.getElementById(elems[i].tempID);
frag.appendChild(elem);
if((elem.id).substr(0,10)=='tempSortID')
elem.removeAttribute('id');
}
parent.appendChild(frag);
elems=null;
returnparent.prevSort;//notcurrentlyused
};
varAddSortToTables=function(){
//..iftablehasclass-name'sortIt'
vartables=document.getElementsByTagName('table'),i,j,
tblLen,tbl,hdrs,hdrsLen;
functionPreserveSortScope(a,b,c,d){
returnfunction(){
//assigntheSortElementsfn.toatableheader
SortElements(a,b,c,d);
}
}
//addsortingtotableheaders
for(i=0,tblLen=tables.length;i<tblLen;i++){
tbl=tables[i];
if(tbl.className.indexOf('sortIt')+1){
hdrs=tbl.getElementsByTagName('th');
if(hdrs){
for(j=0,hdrsLen=hdrs.length;j<hdrsLen;j++){
AddEvent(hdrs[j],'click',PreserveSortScope(tbl,'tr','td',j));
//ifthere'snotitlealready,add"Clicktosort"
if(!hdrs[j].title)hdrs[j].setAttribute('title',
'Clicktosort');
}
}
}
}
};
varAddSortByDate=function(tbl,col,dateMask){
//Input:thetablename(orobject),acolumnindex(orarray)
//andadatemask('dd-mmm-yy')
//AddsasortBy='date'propertytothefirstrow
//willignorethefirstrow,assumingitisaheaderrow
vari,rLen,cell;
while(col.length)AddSortByDate(tbl,col.pop(),dateMask);
if((colinstanceofArray)||isNaN(col))return;
vartbl=(typeoftbl==='string')?document.getElementById(tbl):tbl;
tbl.rows[0].cells[col].sortBy='date';
AddSortByDate2(tbl,'tr','td',col,dateMask);
};
varAddSortByDate2=function(parentEl,childTag,colTag,colIndex,dateMask){
varkids,startAt=0,i,rLen,cell;
varparent=(typeofparentEl==='string')?
document.getElementById(parentEl):parentEl;
if(parent.nodeName.toLowerCase()=='table'){
parent=parent.tBodies[0]||parent;
startAt=(parent.rows[0].cells[0].nodeName.toLowerCase()=='th')*1;
}
kids=parent.getElementsByTagName(childTag);
for(i=startAt,rLen=kids.length;i<rLen;i++){
cell=kids[i].getElementsByTagName(colTag)[colIndex];
if(cell){
if(typeofcell.numberValue!='undefined')deletecell.numberValue;
//theaboveenablesswitchingfromanumbertoadatesort
//(althoughv.unlikely)
if(cell.getAttribute('sort')){
//usesortattributeifpresent
cell.dateValue=newDate(cell.getAttribute('sort'));
}else{
cell.dateValue=newDate(StringToDate(cell.firstChild.nodeValue,
dateMask));
}
if(cell.dateValue.toString()=="NaN"||cell.dateValue.toString()==
"InvalidDate"){
cell.dateValue=0;
}
}
}
};
varAddSortByNumber=function(tbl,col){
//colisacolumnindexorarrayofindices
//willignorethefirstrow,assumingitisaheaderrow
vari,rLen,cell,tempNum;
while(col.length)AddSortByNumber(tbl,col.pop());
if((colinstanceofArray)||isNaN(col))return;
tbl=(typeoftbl==='string')?document.getElementById(tbl):tbl;
tbl.rows[0].cells[col].sortBy='number';
AddSortByNumber2(tbl,'tr','td',col);
};
varAddSortByNumber2=function(parentEl,childTag,colTag,colIndex){
varkids,startAt=0,i,rLen,cell,tempNum;
varparent=(typeofparentEl==='string')?
document.getElementById(parentEl):parentEl;
if(parent.nodeName.toLowerCase()=='table'){
parent=parent.tBodies[0]||parent;
startAt=(parent.rows[0].cells[0].nodeName.toLowerCase()=='th')*1;
}
kids=parent.getElementsByTagName(childTag);
for(i=startAt,rLen=kids.length;i<rLen;i++){
cell=kids[i].getElementsByTagName(colTag)[colIndex];
if(cell){
if(typeofcell.dateValue!='undefined')deletecell.dateValue;
//theaboveenablesswitchingfromadatetoanumbersort
//(althoughv.unlikely)
tempNum=cell.getAttribute('sort')||cell.firstChild.nodeValue;
tempNum=tempNum.replace(/[^0-9.-]/g,'');
cell.numberValue=parseFloat(tempNum);
if(isNaN(cell.numberValue))
cell.numberValue=0.0;
}
}
};
varStringToDate=function(sDate,sFormat,cutOff){
//Input:adatevalueasastring,it'sformatasastringe.g.'dd-mmm-yy'
//Optional:acutoff(integer)for2digityears.
//Ifno'd'appearsintheformatstringthenthe1stofthemonthisassumed.
//Iftheyearis20andthecut-offis30thenthevaluewillbeconverted
//to2020;iftheyearis40thenthiswillbeconvertedto1940.
//Ifnocut-offissuppliedthen'20'willbepre-pendedtotheyear(YY).
//Output:astringintheformat'YYYY/MM/DD'or''
//Willnotattempttoconvertcertaincombinationse.g.DMM,MDD,DDM,YYYYD.
varsParsed,fndSingle;
//sParsedwillbeconstructedintheformat'YYYY/MM/DD'
sDate=sDate.toString().toUpperCase();
sFormat=sFormat.toUpperCase();
if(sFormat.search(/MMMM|MMM/)+1){//replaceMar/Marchwith03,etc.
sDate=sDate.replace(newRegExp('('+ShortMths.join('|')+')[A-Z]*','gi'),
function(m){
vari=ShortMths.indexOf(m.charAt(0).toUpperCase()+
m.substr(1,2).toLowerCase())+1;
return((i<10)?"0"+i:""+i).toString();
});
sFormat=sFormat.replace(/MMMM|MMM/g,'MM');
}
if(sFormat.search(/DDDD|DDD/)+1){//replaceTue/Tuesday,etc.with''
sDate=sDate.replace(newRegExp('('+ShortDays.join('|')+')[A-Z]*','gi'),'');
sFormat=sFormat.replace(/DDDD|DDD/g,'');
}
sDate=sDate.replace(/(^|\D)(\d)(?=\D|$)/g,function($0,$1,$2){
//singledigits2with02
return$1+'0'+$2;
});
sFormat=sFormat.replace(/(^|[^DMY])(D|M)(?=[^DMY]|$)/g,function($0,$1,$2){
return$1+$2+$2;//replaceDorMwithDDandMM
});
//aretherestillsingleDsorMs?
fndSingle=sFormat.search(/(^|[^D])D([^D]|$)|(^|[^M])M([^M]|$)/)+1;
if(fndSingle)return'';//donotattempttoparse,forexample,'DMM'
sFormat=sFormat.replace(/(^|[^Y])(YY)(?=[^Y]|$)/g,function($0,$1,$2,index){
vartempDate=sDate.substr(0,index+1);
tempDate+=(cutOff)?((parseInt(sDate.substr(index+1,2),10)>cutOff)?
'19':'20'):'20';
tempDate+=sDate.substr(index+1);
sDate=tempDate;
return$1+$2+$2;
});
sParsed=('YYYY/MM/DD').replace(/YYYY|MM|DD/g,function(m){
return(sFormat.indexOf(m)+1)?
sDate.substr(sFormat.indexOf(m),m.length):'';
});
if(sParsed.charAt(0)=='/'){
//ifnoyearspecified,assumethecurrentyear
sParsed=(newDate().getFullYear())+sParsed;
}
if(sParsed.charAt(sParsed.length-1)=='/'){
//ifnodate,assumethe1stofthemonth
sParsed+='01';
}
//shouldendupwith10characters..
return(sParsed.length==10)?sParsed:'';
};
希望本文所述对大家的javascript程序设计有所帮助。