JavaScript对表格或元素按文本,数字或日期排序的方法_javascript技巧
程序员文章站
2022-05-22 20:58:01
...
本文实例讲述了JavaScript对表格或元素按文本,数字或日期排序的方法。分享给大家供大家参考。具体实现方法如下:
// Sorting table columns correctly by text, number or date. There are other // versions, plugins, etc., for this but they either are restricted to specific // date formats, or require EVERY row-element to be given a sort attribute; mine // can handle many different date and number formats, and even allows for specific // cells that may not conform to the overall date/number format for that column. // My version also enables sorting of element hierarchies: such as a DIV containing // P-paragraphs and SPANs - this could even be an image-gallery containing prices // or dates within spans. Very efficient as well!! // Example: andrew.dx.am/sortgallerydel.html // AddSortToTables(); will make the table headers clickable, to sort columns in // ascending or descending order, for any tables with class="sortIt". // SortTable(tbl, col); will sort the table (tbl is an id or table object) by // the supplied column index (indexed from 0) in ascending or descending order. // AddSortByDate(tbl, col, dateMask); enables sorting of a column by date, // specified by a date-mask such as 'dd-mmm-yy'. // AddSortByNumber(tbl, col); enables sorting of a column by number. This assumes a // period . as the decimal separator (if present); it ignores any other non-numeric // characters. // SortElements(parentEl, childTag, colTag, colIndex); will sort (non-table) // elements in ascending or descending order. For example, an UL containing LIs // and SPANs. colIndex specifies which span to sort; there may be more than one in // the LI (0 indexed). // Example: SortElements('divid', 'p', 'span', 2); // 3rd span within each paragraph. // // AddSortByDate2(parentEl, childTag, colTag, colIndex, dateMask); and // AddSortByNumber2(parentEl, childTag, colTag, colIndex) // provide the same feature-set as AddSortByDate and AddSortByNumber does // for tables, but for element hierarchies. // If there are dates or numbers in a column (or element) which don't meet the // date-mask or number formatting necessary to sort correctly, then these individual // elements can be given the attribute "sort" and they will still sort correctly! // For example, with a date columnwill still sort a // cell correctly. (This format 'YYYY/MM/DD' will be converted into a Date() object.) var MonthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var DayNames = [ "Sunday", "Monday", "Tueday", "Wednesday", "Thursday", "Friday", "Saturday" ]; var ShortMths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var ShortDays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; var AddEvent = function (elem, eventType, func) { // Helper function. if ( elem.addEventListener ) AddEvent = function (elem, eventType, func) { elem.addEventListener(eventType, func, false); }; else if ( 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); }; // Sort methods/algorithms attributed: var SortTable = function (tbl, col) { // could be called directly SortElements(tbl, 'tr', 'td', col); }; var SortElements = function (parentEl, childTag, colTag, colIndex) { // example use: SortElements('table1','tr','td',2) // or SortElements('list1','li') // or SortElements('divName','p','span',3) var i, j, cTags = {}, startAt = 0, childLen, aChild, elem, sortBy, content, elems = [], sortedLen, frag, hdrsLen, hdr; var parent = (typeof parentEl === 'string') ? document.getElementById(parentEl) : parentEl; var AscText = function (a, b) { // sort() by .data as text var x = a.data, y = b.data, xNum = parseFloat(x), yNum = parseFloat(y); // check if each begin with a number.. if ( !isNaN(xNum) && !isNaN(yNum) && (xNum - yNum) ) return xNum - yNum; return ((x y) ? 1 : 0)); }; var DescText = function (a, b) { // sort() by .data var x = a.data, y = b.data, xNum = parseFloat(x), yNum = parseFloat(y); // check if each begin with a number.. if ( !isNaN(xNum) && !isNaN(yNum) && (yNum - xNum) ) return yNum - xNum; return ((x > y) ? -1 : ((x for a date. 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 }; } } // The following will determine if the table/etc has already been sorted // by the same column or tag. If so, it will sort in ascending or descending // order. It creates custom element properties to the parent element to // remember the previous sort details. if ( typeof colIndex == 'undefined' ) colIndex = 0; if ( parent.prevTag && parent.prevTag == ((typeof colTag == 'undefined') ? childTag : colTag) ) { if (parent.prevCol == colIndex) { // sorting by the same column as previously parent.prevSort = (parent.prevSort == 'asc') ? 'desc' : 'asc'; } else { // sorting by any other column parent.prevCol = colIndex; parent.prevSort = 'asc'; } } else { // sorting for the 1st time or by a different tag parent.prevTag = ((typeof colTag == 'undefined') ? childTag : colTag); parent.prevCol = colIndex; parent.prevSort = 'asc'; } if ( parent.prevSort === 'desc' ) { // 'desc' WILL BE the previous sort order.. 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 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) == '/') { // if no year specified, assume the current year sParsed = (new Date().getFullYear()) + sParsed; } if (sParsed.charAt(sParsed.length - 1) == '/') { // if no date, assume the 1st of the month sParsed += '01'; } // should end up with 10 characters.. return ( sParsed.length == 10 ) ? sParsed : ''; }; 希望本文所述对大家的javascript程序设计有所帮助。
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
相关文章
相关视频
- javascript怎么将值类型强制转为字符串
- javascript中什么是位运算符
- 总结分享: 6 种JavaScript的打断点的方...
- javascript怎么判断字符串是否是数字
- JavaScript对表格或元素按文本,数字或日期...
专题推荐
- 独孤九贱-php全栈开发教程
全栈 170W+
主讲:Peter-Zhu 轻松幽默、简短易学,非常适合PHP学习入门
- 玉女心经-web前端开发教程
入门 80W+
主讲:灭绝师太 由浅入深、明快简洁,非常适合前端学习入门
- 天龙八部-实战开发教程
实战 120W+
主讲:西门大官人 思路清晰、严谨规范,适合有一定web编程基础学习
- 最新文章
- 热门排行
网友评论
文明上网理性发言,请遵守 新闻评论服务协议
我要评论