บทความนี้อธิบายวิธีการใช้งานของการเรียงลำดับส่วนหัว JS แบ่งปันสำหรับการอ้างอิงของคุณ
วิธีการใช้งานเฉพาะมีดังนี้:
การคัดลอกรหัสมีดังนี้:
<script type = "text/javascript">
// ว่าจะเรียงลำดับ
var isDescending = true;
-
* แถวที่จะจัดเรียงจะต้องวางไว้ในแท็ก <tbody> </tbody>
* TableID: Sort Table ID
* Colno: หมายเลขคอลัมน์ที่เรียงลำดับนั่นคือคอลัมน์ใดเริ่มจาก 0
* Startrowno: หมายเลขบรรทัดเริ่มต้นของการเรียงลำดับเริ่มต้นจาก 0
* SortLength: จำนวนแถวที่จะเรียงลำดับ
* ประเภท: ประเภทของคอลัมน์การเรียงลำดับ
-
Function Sort (TableId, Colno, Startrowno, SortLength, Type)
-
// หากจำนวนแถวที่จะเรียงลำดับคือ 1 หรือ 0 ดังนั้นจะไม่มีการดำเนินการเรียงลำดับ
if (sortLength <= 1) {
กลับ;
-
var currtable = document.getElementById (tableId);
var theheader = currtable.outerhtml.substring (0, currtable.outerhtml.indexof ('<tbody>')+7)
var thefooter = currtable.outerhtml.substring (currtable.outerhtml.indexof ('</tbody>')-8);
// จำนวนแถวที่นี่คือจำนวนแถวที่ลบตารางส่วนหัวและแถวตาราง
var therows = อาร์เรย์ใหม่ (sortLength);
// ยุบข้อมูลในตาราง
สำหรับ (i = startrowno; i <sortlength+startrowno; i ++)
-
therows [i-startrowno] = อาร์เรย์ใหม่ (currtable.rows [i] .cells [colno] .innertext.toLowercase (), currtable.rows [i] .outerhtml);
-
if (type.touppercase () == 'number')
-
therows.sort (เปรียบเทียบ);
-
อื่นถ้า (type.touppercase () == 'วันที่')
therows.sort (เปรียบเทียบ);
อย่างอื่นถ้า (type.touppercase () == 'สตริง')
therows.sort (เปรียบเทียบ);
var tableInfo = ''
สำหรับ (j = 0; j <therows.length; j ++)
-
tableInfo+= therows [j] [1];
-
isDescending =! isDescending;
currtable.outerhtml = theheader + tableinfo + thefooter;
กลับ ;
-
// เปรียบเทียบตัวเลข
ฟังก์ชันเปรียบเทียบ (x, y)
-
// แปลงข้อมูลรูปแบบสกุลเงิน
a = x [0] .ExCludechars (","). trim ();
b = y [0] .Excludechars (","). trim ();
if (a == "") {a = 0;}
if (b == "") {b = 0;}
ถ้า (isdescending)
-
กลับ parsefloat (b) - parsefloat (a);
-
อื่น
-
กลับ parsefloat (a) - parsefloat (b);
-
-
// เปรียบเทียบสตริง
ฟังก์ชั่นเปรียบเทียบ (x, y)
-
ถ้า (isdescending)
-
if (x [0]> y [0]) return -1;
อื่นถ้า (x [0] <y [0]) กลับ 1;
กลับมาอีก 0;
-
อื่น
-
if (x [0] <y [0]) return -1;
อื่นถ้า (x [0]> y [0]) กลับ 1;
กลับมาอีก 0;
-
-
// เปรียบเทียบเวลา
ฟังก์ชั่นเปรียบเทียบ (x, y) {
var arr = x [0] .split ("-");
var startTime = วันที่ใหม่ (arr [0], arr [1], arr [2]);
var startTimes = startTime.getTime ();
var arrrs = y [0] .split ("-");
var lktime = วันที่ใหม่ (arrs [0], arrs [1], arrs [2]);
var lktimes = lktime.getTime ();
ถ้า (isdescending)
-
ส่งคืน lktimes - starttimes;
-
อื่น
-
return starttimes - lktimes;
-
-
// ลบสตริงที่ระบุทั้งหมดในสตริง
string.prototype.excludechars = function (chars) {
การจับคู่ var = ใหม่ regexp (chars, "g");
ส่งคืนสิ่งนี้กลับสถานที่ (การจับคู่, '');
-
</script>
ฉันหวังว่าบทความนี้จะเป็นประโยชน์กับการเขียนโปรแกรม JavaScript ของทุกคน