search
HomeWeb Front-endJS TutorialJavaScript method to implement table click sorting_javascript skills

本文实例讲述了JavaScript实现表格点击排序的方法。分享给大家供大家参考。具体分析如下:

这里实现基于JS的表格点击排序效果,可以根据表格内的数据大小自动按顺序排列,股票网站常会见到这种功能。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>表格排序</title>
</head>
<STYLE type=text/css>TABLE {
 BORDER-RIGHT: #000000 2px solid; BORDER-TOP: #000000 2px solid;
 BORDER-LEFT: #000000 2px solid; BORDER-BOTTOM: #000000 2px solid;
 border-spacing: 0px; cell-spacing: 0px
}
TD {
 PADDING-RIGHT: 0.5em; PADDING-LEFT: 0.5em; FONT-SIZE: 10pt;
 PADDING-BOTTOM: 2px; PADDING-TOP: 2px; 
 FONT-FAMILY: Arial, Helvetica, sans-serif; WHITE-SPACE: nowrap
}
TH {
 PADDING-RIGHT: 0.5em; PADDING-LEFT: 0.5em; FONT-SIZE: 10pt;
 PADDING-BOTTOM: 2px; PADDING-TOP: 2px;
 FONT-FAMILY: Arial, Helvetica, sans-serif; WHITE-SPACE: nowrap
}
TD.numeric {
 TEXT-ALIGN: right
}
TH {
 BACKGROUND-COLOR: #c0c0c0
}
TH.mainHeader {
 COLOR: #ffffff; BACKGROUND-COLOR: #808080; TEXT-ALIGN: left
}
TH A {
 COLOR: #000080; TEXT-DECORATION: none
}
TH A:visited {
 COLOR: #000080
}
TH A:active {
 COLOR: #800000; TEXT-DECORATION: underline
}
TH A:hover {
 COLOR: #800000; TEXT-DECORATION: underline
}
TR.alternateRow {
 BACKGROUND-COLOR: #e0e0e0
}
TD.sortedColumn {
 BACKGROUND-COLOR: #f0f0f0
}
TH.sortedColumn {
 BACKGROUND-COLOR: #b0b0b0
}
TR.alternateRow TD.sortedColumn {
 BACKGROUND-COLOR: #d0d0d0
}
</STYLE>
<SCRIPT type=text/javascript>
function sortTable(id, col, rev) {
 var tblEl = document.getElementById(id);
 if (tblEl.reverseSort == null) {
  tblEl.reverseSort = new Array();
  tblEl.lastColumn = 1;
 }
 if (tblEl.reverseSort[col] == null)
  tblEl.reverseSort[col] = rev;
 if (col == tblEl.lastColumn)
  tblEl.reverseSort[col] = !tblEl.reverseSort[col];
 tblEl.lastColumn = col;
 var oldDsply = tblEl.style.display;
 tblEl.style.display = "none";
 var tmpEl;
 var i, j;
 var minVal, minIdx;
 var testVal;
 var cmp;
 for (i = 0; i < tblEl.rows.length - 1; i++) {
  minIdx = i;
  minVal = getTextValue(tblEl.rows[i].cells[col]);
  for (j = i + 1; j < tblEl.rows.length; j++) {
   testVal = getTextValue(tblEl.rows[j].cells[col]);
   cmp = compareValues(minVal, testVal);
   if (tblEl.reverseSort[col])
    cmp = -cmp;
   if (cmp == 0 && col != 1)
    cmp = compareValues(getTextValue(tblEl.rows[minIdx].cells[1]),
              getTextValue(tblEl.rows[j].cells[1]));
   if (cmp > 0) {
    minIdx = j;
    minVal = testVal;
   }
  }
  if (minIdx > i) {
   tmpEl = tblEl.removeChild(tblEl.rows[minIdx]);
   tblEl.insertBefore(tmpEl, tblEl.rows[i]);
  }
 }
 makePretty(tblEl, col);
 setRanks(tblEl, col, rev);
 tblEl.style.display = oldDsply;
 return false;
}
if (document.ELEMENT_NODE == null) {
 document.ELEMENT_NODE = 1;
 document.TEXT_NODE = 3;
}
function getTextValue(el) {
 var i;
 var s;
 s = "";
 for (i = 0; i < el.childNodes.length; i++)
  if (el.childNodes[i].nodeType == document.TEXT_NODE)
   s += el.childNodes[i].nodeValue;
  else if (el.childNodes[i].nodeType == document.ELEMENT_NODE && 
       el.childNodes[i].tagName == "BR")
   s += " ";
  else
   // Use recursion to get text within sub-elements.
   s += getTextValue(el.childNodes[i]);
 return normalizeString(s);
}
function compareValues(v1, v2) {
 var f1, f2;
 f1 = parseFloat(v1);
 f2 = parseFloat(v2);
 if (!isNaN(f1) && !isNaN(f2)) {
  v1 = f1;
  v2 = f2;
 }
 // Compare the two values.
 if (v1 == v2)
  return 0;
 if (v1 > v2)
  return 1
 return -1;
}
var whtSpEnds = new RegExp("^\\s*|\\s*$", "g");
var whtSpMult = new RegExp("\\s\\s+", "g");
function normalizeString(s) {
 s = s.replace(whtSpMult, " "); // Collapse any multiple whites space.
 s = s.replace(whtSpEnds, "");  // Remove leading or trailing white space.
 return s;
}
var rowClsNm = "alternateRow";
var colClsNm = "sortedColumn";
var rowTest = new RegExp(rowClsNm, "gi");
var colTest = new RegExp(colClsNm, "gi");
function makePretty(tblEl, col) {
 var i, j;
 var rowEl, cellEl;
 for (i = 0; i < tblEl.rows.length; i++) {
  rowEl = tblEl.rows[i];
  rowEl.className = rowEl.className.replace(rowTest, "");
  if (i % 2 != 0)
   rowEl.className += " " + rowClsNm;
  rowEl.className = normalizeString(rowEl.className);
  for (j = 2; j < tblEl.rows[i].cells.length; j++) {
   cellEl = rowEl.cells[j];
   cellEl.className = cellEl.className.replace(colTest, "");
   if (j == col)
    cellEl.className += " " + colClsNm;
   cellEl.className = normalizeString(cellEl.className);
  }
 }
 var el = tblEl.parentNode.tHead;
 rowEl = el.rows[el.rows.length - 1];
 for (i = 2; i < rowEl.cells.length; i++) {
  cellEl = rowEl.cells[i];
  cellEl.className = cellEl.className.replace(colTest, "");
  if (i == col)
   cellEl.className += " " + colClsNm;
   cellEl.className = normalizeString(cellEl.className);
 }
}
function setRanks(tblEl, col, rev) {
 var i  = 0;
 var incr = 1;
 if (tblEl.reverseSort[col])
  rev = !rev;
 if (rev) {
  incr = -1;
  i = tblEl.rows.length - 1;
 }
 var count  = 1;
 var rank  = count;
 var curVal;
 var lastVal = null;
 while (col > 1 && i >= 0 && i < tblEl.rows.length) {
  curVal = getTextValue(tblEl.rows[i].cells[col]);
  if (lastVal != null && compareValues(curVal, lastVal) != 0)
    rank = count;
  tblEl.rows[i].rank = rank;
  lastVal = curVal;
  count++;
  i += incr;
 }
 var rowEl, cellEl;
 var lastRank = 0;
 for (i = 0; i < tblEl.rows.length; i++) {
  rowEl = tblEl.rows[i];
  cellEl = rowEl.cells[0];
  while (cellEl.lastChild != null)
   cellEl.removeChild(cellEl.lastChild);
  if (col > 1 && rowEl.rank != lastRank) {
   cellEl.appendChild(document.createTextNode(rowEl.rank));
   lastRank = rowEl.rank;
  }
 }
}
</SCRIPT>
</HEAD>
<BODY>
<!-- Offensive statistics table. -->
<TABLE cellSpacing=0 cellPadding=0 border=0>
 <THEAD>
 <TR>
  <TH class=mainHeader colSpan=11>NFL 2001 Offensive Stats</TH></TR>
 <TR>
  <TH style="TEXT-ALIGN: left">Rank</TH>
  <TH style="TEXT-ALIGN: left"><A title="Team Name" 
   onclick="this.blur(); return sortTable('offTblBdy', 1, false);" 
   href="#">Team</A></TH>
  <TH><SPAN title="Games Played">Gms</SPAN></TH>
  <TH><A title="Total Yards" 
   onclick="this.blur(); return sortTable('offTblBdy', 3, true);" 
   href="#">Yds</A></TH>
  <TH><A title="Yards Per Game" 
   onclick="this.blur(); return sortTable('offTblBdy', 4, true);" 
   href="#">Yds/G</A></TH>
  <TH><A title="Total Rushing Yards" 
   onclick="this.blur(); return sortTable('offTblBdy', 5, true);" 
   href="#">RuYds</A></TH>
  <TH><A title="Rushing Yards Per Game" 
   onclick="this.blur(); return sortTable('offTblBdy', 6, true);" 
   href="#">RuYds/G</A></TH>
  <TH><A title="Total Passing Yards" 
   onclick="this.blur(); return sortTable('offTblBdy', 7, true);" 
   href="#">PaYds</A></TH>
  <TH><A title="Passing Yards Per Game" 
   onclick="this.blur(); return sortTable('offTblBdy', 8, true);" 
   href="#">PaYds/G</A></TH>
  <TH><A title="Total Points Scored" 
   onclick="this.blur(); return sortTable('offTblBdy', 9, true);" 
   href="#">Pts</A></TH>
  <TH><A title="Points Per Game" 
   onclick="this.blur(); return sortTable('offTblBdy', 10, true);" 
   href="#">Pts/G</A></TH></TR></THEAD>
 <TBODY id=offTblBdy>
 <TR>
  <TD class=numeric></TD>
  <TD>Arizona</TD>
  <TD class=numeric>16</TD>
  <TD class=numeric>4898</TD>
  <TD class=numeric>306.1</TD>
  <TD class=numeric>1449</TD>
  <TD class=numeric>90.6</TD>
  <TD class=numeric>3449</TD>
  <TD class=numeric>215.6</TD>
  <TD class=numeric>295</TD>
  <TD class=numeric>18.4</TD></TR>
 <TR class=alternateRow>
  <TD class=numeric></TD>
  <TD>Atlanta</TD>
  <TD class=numeric>16</TD>
  <TD class=numeric>5070</TD>
  <TD class=numeric>316.9</TD>
  <TD class=numeric>1773</TD>
  <TD class=numeric>110.8</TD>
  <TD class=numeric>3297</TD>

  <TD class=numeric>206.1</TD>
  <TD class=numeric>291</TD>
  <TD class=numeric>18.2</TD></TR>
<TR>
<TD class=numeric></TD>
  <TD>Detroit</TD>
  <TD class=numeric>16</TD>
  <TD class=numeric>4994</TD>
  <TD class=numeric>312.1</TD>
  <TD class=numeric>1398</TD>
  <TD class=numeric>87.4</TD>
  <TD class=numeric>3596</TD>
  <TD class=numeric>224.8</TD>
  <TD class=numeric>270</TD>
  <TD class=numeric>16.9</TD></TR>
 <TR class=alternateRow>
  <TD class=numeric></TD>
  <TD>Jacksonville</TD>
  <TD class=numeric>16</TD>
  <TD class=numeric>4840</TD>
  <TD class=numeric>302.5</TD>
  <TD class=numeric>1600</TD>
  <TD class=numeric>100.0</TD>
  <TD class=numeric>3240</TD>
  <TD class=numeric>202.5</TD>
  <TD class=numeric>294</TD>
  <TD class=numeric>18.4</TD></TR>
 <TR>
  <TD class=numeric></TD>
  <TD>Kansas City</TD>
  <TD class=numeric>16</TD>
  <TD class=numeric>5673</TD>
  <TD class=numeric>354.6</TD>
  <TD class=numeric>2008</TD>
  <TD class=numeric>125.5</TD>
  <TD class=numeric>3665</TD>
  <TD class=numeric>229.1</TD>
  <TD class=numeric>320</TD>
  <TD class=numeric>20.0</TD></TR>
 <TR class=alternateRow>
  <TD class=numeric></TD>
  <TD>Miami</TD>
  <TD class=numeric>16</TD>
  <TD class=numeric>4821</TD>
  <TD class=numeric>301.3</TD>
  <TD class=numeric>1664</TD>
  <TD class=numeric>104.0</TD>
  <TD class=numeric>3157</TD>
  <TD class=numeric>197.3</TD>
  <TD class=numeric>344</TD>
  <TD class=numeric>21.5</TD></TR>
 <TR>
  <TD class=numeric></TD>
  <TD>Minnesota</TD>
  <TD class=numeric>16</TD>
  <TD class=numeric>5006</TD>
  <TD class=numeric>333.7</TD>
  <TD class=numeric>1523</TD>
  <TD class=numeric>101.5</TD>
  <TD class=numeric>3483</TD>
  <TD class=numeric>232.2</TD>
  <TD class=numeric>287</TD>
  <TD class=numeric>19.1</TD></TR>
 <TR class=alternateRow>
  <TD class=numeric></TD>
  <TD>New England</TD>
  <TD class=numeric>16</TD>
  <TD class=numeric>4882</TD>
  <TD class=numeric>305.1</TD>
  <TD class=numeric>1793</TD>
  <TD class=numeric>112.1</TD>
  <TD class=numeric>3089</TD>
  <TD class=numeric>193.1</TD>
  <TD class=numeric>371</TD>
  <TD class=numeric>23.2</TD></TR>
 <TR>
  <TD class=numeric></TD>
  <TD>New Orleans</TD>
  <TD class=numeric>16</TD>
  <TD class=numeric>5226</TD>
  <TD class=numeric>326.6</TD>
  <TD class=numeric>1712</TD>
  <TD class=numeric>107.0</TD>
  <TD class=numeric>3514</TD>
  <TD class=numeric>219.6</TD>
  <TD class=numeric>333</TD>
  <TD class=numeric>20.8</TD></TR>
 <TR class=alternateRow>
  <TD class=numeric></TD>
  <TD>New York Giants</TD>
  <TD class=numeric>16</TD>
  <TD class=numeric>5335</TD>
  <TD class=numeric>333.4</TD>
  <TD class=numeric>1777</TD>
  <TD class=numeric>111.1</TD>
  <TD class=numeric>3558</TD>
  <TD class=numeric>222.4</TD>
  <TD class=numeric>294</TD>
  <TD class=numeric>18.4</TD></TR>
</TBODY></TABLE>
</BODY>
</HTML>

希望本文所述对大家的javascript程序设计有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment