JavaScript对表格或元素按文本,数字或日期排序的方法

   本文实例讲述了JavaScript对表格或元素按文本,数字或日期排序的方法。分享给大家供大家参考。具体实现方法如下:

  ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344

// 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 column <td sort="2012/12/20"> will 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 : ((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 < y) ? 1 : 0));
};
var AscNum = function (a, b) { // used with dates as well
return a.data - b.data;
};
var DescNum = function (a, b) {
return b.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 ( typeof colIndex == 'undefined' ) {
sortBy = 'text'; // sort simple lists or paragraphs as text
}
for (i = startAt, childLen = cTags.length; i < childLen; i++) {
// ..go forward examining each child
aChild = cTags[i];
elem = (colTag) ? aChild.getElementsByTagName(colTag)[colIndex] : aChild;
if (elem) {
if ( !sortBy ) { // sorting non-table columns..
sortBy = (typeof elem.numberValue != 'undefined') ? 'number' :
((typeof elem.dateValue != 'undefined') ? 'date' : 'text');
}
switch (sortBy) {
// You can supply 'sort' attributes to enable sorting of numbers, etc.
// For example, <td sort='2011/02/12'> 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 < 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;
return parent.prevSort; // not currently used
};
var AddSortToTables = function () {
// ..if table has class-name 'sortIt'
var tables = document.getElementsByTagName('table'), i, j,
tblLen, tbl, hdrs, hdrsLen;
function PreserveSortScope(a,b,c,d) {
return function () {
// assign the SortElements fn. to a table header
SortElements(a, b, c, d);
}
}
// add sorting to table headers
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));
// if there's no title already, add "Click to sort"
if ( !hdrs[j].title ) hdrs[j].setAttribute('title',
'Click to sort');
}
}
}
}
};
var AddSortByDate = function (tbl, col, dateMask) {
// Input: the table name (or object), a column index (or array)
// and a date mask ('dd-mmm-yy')
// Adds a sortBy = 'date' property to the first row
// will ignore the first row, assuming it is a header row
var i, rLen, cell;
while ( col.length ) AddSortByDate(tbl,col.pop(),dateMask);
if ((col instanceof Array) || isNaN(col)) return;
var tbl = (typeof tbl === 'string') ? document.getElementById(tbl) : tbl;
tbl.rows[0].cells[col].sortBy = 'date';
AddSortByDate2(tbl, 'tr', 'td', col, dateMask);
};
var AddSortByDate2 = function (parentEl, childTag, colTag, colIndex, dateMask) {
var kids, startAt = 0, i, rLen, cell;
var parent = (typeof parentEl === '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 ( typeof cell.numberValue != 'undefined' ) delete cell.numberValue;
// the above enables switching from a number to a date sort
// (although v. unlikely)
if (cell.getAttribute('sort')) {
// use sort attribute if present
cell.dateValue = new Date(cell.getAttribute('sort'));
} else {
cell.dateValue = new Date(StringToDate(cell.firstChild.nodeValue,
dateMask));
}
if (cell.dateValue.toString() == "NaN" || cell.dateValue.toString() ==
"Invalid Date") {
cell.dateValue = 0;
}
}
}
};
var AddSortByNumber = function (tbl, col) {
// col is a column index or array of indices
// will ignore the first row, assuming it is a header row
var i, rLen, cell, tempNum;
while ( col.length ) AddSortByNumber(tbl,col.pop());
if ((col instanceof Array) || isNaN(col)) return;
tbl = (typeof tbl === 'string') ? document.getElementById(tbl) : tbl;
tbl.rows[0].cells[col].sortBy = 'number';
AddSortByNumber2(tbl,'tr','td',col);
};
var AddSortByNumber2 = function (parentEl, childTag, colTag, colIndex) {
var kids, startAt = 0, i, rLen, cell, tempNum;
var parent = (typeof parentEl === '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 ( typeof cell.dateValue != 'undefined' ) delete cell.dateValue;
// the above enables switching from a date to a number sort
// (although v. 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;
}
}
};
var StringToDate = function (sDate, sFormat, cutOff) {
// Input: a date value as a string, it's format as a string e.g. 'dd-mmm-yy'
// Optional: a cutoff (integer) for 2 digit years.
// If no 'd' appears in the format string then the 1st of the month is assumed.
// If the year is 20 and the cut-off is 30 then the value will be converted
// to 2020; if the year is 40 then this will be converted to 1940.
// If no cut-off is supplied then '20' will be pre-pended to the year (YY).
// Output: a string in the format 'YYYY/MM/DD' or ''
// Will not attempt to convert certain combinations e.g. DMM, MDD, DDM, YYYYD.
var sParsed, fndSingle;
// sParsed will be constructed in the format 'YYYY/MM/DD'
sDate = sDate.toString().toUpperCase();
sFormat = sFormat.toUpperCase();
if (sFormat.search(/MMMM|MMM/) + 1) { // replace Mar/March with 03, etc.
sDate = sDate.replace(new RegExp('(' + ShortMths.join('|') + ')[A-Z]*', 'gi'),
function (m) {
var i = 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) { // replace Tue/Tuesday, etc. with ''
sDate = sDate.replace(new RegExp('(' + ShortDays.join('|') + ')[A-Z]*', 'gi'),'');
sFormat = sFormat.replace(/DDDD|DDD/g, '');
}
sDate = sDate.replace(/(^|D)(d)(?=D|$)/g, function($0, $1, $2) {
// single digits 2 with 02
return $1 + '0' + $2;
});
sFormat = sFormat.replace(/(^|[^DMY])(D|M)(?=[^DMY]|$)/g, function($0, $1, $2){
return $1 + $2 + $2; // replace D or M with DD and MM
});
// are there still single Ds or Ms?
fndSingle = sFormat.search(/(^|[^D])D([^D]|$)|(^|[^M])M([^M]|$)/)+1;
if ( fndSingle ) return ''; // do not attempt to parse, for example, 'DMM'
sFormat = sFormat.replace(/(^|[^Y])(YY)(?=[^Y]|$)/g, function($0, $1, $2, index) {
var tempDate = 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) == '/') {
// 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程序设计有所帮助。

时间: 2016-05-28

JavaScript对表格或元素按文本,数字或日期排序的方法的相关文章

JavaScript实现获取某个元素相邻兄弟节点的prev与next方法_javascript技巧

本文实例讲述了JavaScript实现获取某个元素相邻兄弟节点的prev与next方法.分享给大家供大家参考,具体如下: /** * 获取相邻元素 * @param ele 参考物元素 * @param type 类型,上一个(1)or下一个(0) * @return 返回查找到的元素Dom对象,无则返回null */ function getNearEle(ele, type) { type = type == 1 ? "previousSibling" : "nextSi

JavaScript使用Max函数返回两个数字中较大数的方法_javascript技巧

本文实例讲述了JavaScript使用Max函数返回两个数字中较大数的方法.分享给大家供大家参考.具体如下: JavaScript的Math对象带有一个max函数用于获取两个数字的较大数,下面的代码详细演示了max的用法 <!DOCTYPE html> <html> <body> <p id="demo"> Click the button to return the highest number of 5 and 10. </p&

SQL字符型字段按数字型字段排序实现方法_Mysql

这是很久之前的就遇到的问题了,去年写了个WP插件:WordPress投票插件Ludou Simple Vote,由于有些使用者需要一个投票排行榜,所以需要用一条SQL来读取按得分排序的文章列表.      Ludou Simple Vote的投票得分结果是以自定义栏目的方式存储在WordPress的postmeta中,分值存放在meta_value字段,而meta_value字段类型是longtext,如果直接使用下面的SQL查询语句来排序: 复制代码 代码如下: ORDER BY `meta_

Knockoutjs控制元素内文本显示的方法:text

Knockout控制元素内文本显示需要使用text绑定方法,此方法相当于在DOM中使用innerText将文本放入到元素中.使用的方法是: <div data-bind="text:myText"></div> 其中,myText可以是字符串.函数.表达式,只要最终返回的结果是字符串即可正常显示.下面列举一些相关例子. 字符串形式 <div data-bind="text:'小虾虎鱼'"></div> 注意:此方式在实

javascript单击表格变成文本输入框

关于动态创建input输入框我们是利用了js dom来操作了,主要是利用了 document.createelement创建了一个input对象,再给对象设置属性. <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="htt

wps表格中怎样将文本格式转为数值格式

  在wps表格中将文本格式转为数值格式的方法: 我们可以先选中所有的文本数字,然后点击wps表格导航上的"数据",如下图所示. 在wps表格的数据选项里,我们找到"分列"图标,点击分列图标,如下图所示. 在wps表格弹出的文本分列向导对话框里,我们所有的设置都是默认的,我们直接点击右下角的完成,如下图所示. OK,此时我们在回到wps表格里来看看,此时文本都变成了数字.如下图所示.

javascript实现表格增删改操作实例详解

 本文实例讲述了javascript实现表格增删改操作的方法.分享给大家供大家参考.具体实现方法如下: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 6

JavaScript中的noscript元素属性位置及作用介绍_javascript技巧

一.<script>元素属性 向XHTML页面中插入JavaScript的主要方法,就是使用<script>元素,该元素有5个属性分别为charset.defer.language.src.type,经常使用的是type.src.defer这三个. 1.type属性的值一般都是text/javascript,该属性是必须的,<script type="text/javascript"/>. 2.src属性的值是*.js外部文件,该属性是可选的,<

javascript jquery对form元素的常见操作详解_javascript技巧

1.下拉框 select : 移除option $("#ID option").each(function(){ if($(this).val() == 111){ $(this).remove(); } }); 添加option $("<option value='111'>UPS Ground</option>").appendTo($("#ID")); 取得下拉选单的选取值 //取下拉選中的文本 $('#testSe