search
HomeWeb Front-endJS TutorialJquery operates table columns and sorts tables

This time I will bring you Jquery to operate table columns and sort tables. What are the precautions for Jquery to operate table columns and sort tables? The following is a practical case, let's take a look.

The main idea of ​​this implementation is: get the column number of the header cell clicked by the mouse, traverse the data rows, get the html in each , and get the html under each tag Correspond to the content in the tag of the obtained column number, and obtain the type attribute value of the tag. Friends who need it can learn about it

There are many Jquery plug-ins that sort tables on the front end , the function is also very powerful. For example, Jquery Data Tables is quite powerful in processing tables. It can sort, search, paging and other operations on tables, but I have not carefully studied its implementation principle.

In order to better understand the principle of sorting tables on the front end, and to further learn Jquery, I decided to use Jquery to implement a small function of sorting tables.
The main idea of ​​this implementation is: get the column number of the table header cell clicked by the mouse, traverse the data rows, get the html in each

, and get the corresponding information under each label. The content in the tag of the column number is obtained, and the type attribute value of the tag is obtained, and the html of , the content of and the type attribute value of are obtained and spliced into a string and add it to the array array, then empty all the HTML in the table , use different methods to compare the contents of according to the different type attribute values, and compare the array array based on the comparison results. Sort, and then reassign the sorted array elements to the empty . If the column has already been sorted, invert the array directly. Three types of sorting rules are provided: numerical, string, and IP address. The string type sorting rule uses the localeCompare method of JavaScript, which supports the sorting of Chinese character strings. Unfortunately, this method is not compatible with Google Chrome. Therefore, the sorting results of Chinese character strings on Google Chrome will be incorrect.

HTML code list
View Code 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<title> 表格排序 </title> 
<meta name="Generator" content="EditPlus"> 
<meta name="Author" content="tschengbin"> 
<meta name="Keywords" content="jquery tableSort"> 
<meta name="Description" content=""> 
<script type="text/javascript" src="jquery-1.8.3.min.js"></script> 
<script type="text/javascript" src="tableSort.js"></script> 
<style type="text/css"> 
p{ 
width: 1024px; 
margin: 0 auto;/*p相对屏幕左右居中*/ 
} 
table{ 
border: solid 1px #666; 
border-collapse: collapse; 
width: 100%; 
cursor: default; 
} 
tr{ 
border: solid 1px #666; 
height: 30px; 
} 
table thead tr{ 
background-color: #ccc; 
} 
td{ 
border: solid 1px #666; 
} 
th{ 
border: solid 1px #666; 
text-align: center; 
cursor: pointer; 
} 
.sequence{ 
text-align: center; 
} 
.hover{ 
background-color: #3399FF; 
} 
</style> 
</head> 
<body> 
<p> 
<table id="tableSort"> 
<thead> 
<tr> 
<th type="number">序号</th> 
<th type="string">书名</th> 
<th type="number">价格(元)</th> 
<th type="string">出版时间</th> 
<th type="number">印刷量(册)</th> 
<th type="ip">IP</th> 
</tr> 
</thead> 
<tbody> 
<tr class="hover"> 
<td class="sequence">1</td> 
<td>狼图腾</td> 
<td>29.80</td> 
<td>2009-10</td> 
<td>50000</td> 
<td>192.168.1.125</td> 
</tr> 
<tr> 
<td class="sequence">2</td> 
<td>孝心不能等待</td> 
<td>29.80</td> 
<td>2009-09</td> 
<td>800</td> 
<td>192.68.1.125</td> 
</tr> 
<tr> 
<td class="sequence">3</td> 
<td>藏地密码2</td> 
<td>28.00</td> 
<td>2008-10</td> 
<td></td> 
<td>192.102.0.12</td> 
</tr> 
<tr> 
<td class="sequence">4</td> 
<td>藏地密码1</td> 
<td>24.80</td> 
<td>2008-10</td> 
<td></td> 
<td>215.34.126.10</td> 
</tr> 
<tr> 
<td class="sequence">5</td> 
<td>设计模式之禅</td> 
<td>69.00</td> 
<td>2011-12</td> 
<td></td> 
<td>192.168.1.5</td> 
</tr> 
<tr> 
<td class="sequence">6</td> 
<td>轻量级 Java EE 企业应用实战</td> 
<td>99.00</td> 
<td>2012-04</td> 
<td>5000</td> 
<td>192.358.1.125</td> 
</tr> 
<tr> 
<td class="sequence">7</td> 
<td>Java 开发实战经典</td> 
<td>79.80</td> 
<td>2012-01</td> 
<td>2000</td> 
<td>192.168.1.25</td> 
</tr> 
<tr> 
<td class="sequence" onclick="sortArray()">8</td> 
<td>Java Web 开发实战经典</td> 
<td>69.80</td> 
<td>2011-11</td> 
<td>2500</td> 
<td>215.168.54.125</td> 
</tr> 
</tbody> 
</table> 
</p> 
</body> 
</html> 

tableSort.js代码清单:
复制代码 代码如下:

View Code 
$(document).ready(function(){ 
var tableObject = $(&#39;#tableSort&#39;);//获取id为tableSort的table对象 
var tbHead = tableObject.children(&#39;thead&#39;);//获取table对象下的thead 
var tbHeadTh = tbHead.find(&#39;tr th&#39;);//获取thead下的tr下的th 
var tbBody = tableObject.children(&#39;tbody&#39;);//获取table对象下的tbody 
var tbBodyTr = tbBody.find(&#39;tr&#39;);//获取tbody下的tr 
var sortIndex = -1; 
tbHeadTh.each(function() {//遍历thead的tr下的th 
var thisIndex = tbHeadTh.index($(this));//获取th所在的列号 
$(this).mouseover(function(){ 
tbBodyTr.each(function(){//编列tbody下的tr 
var tds = $(this).find("td");//获取列号为参数index的td对象集合 
$(tds[thisIndex]).addClass("hover"); 
}); 
}).mouseout(function(){ 
tbBodyTr.each(function(){ 
var tds = $(this).find("td"); 
$(tds[thisIndex]).removeClass("hover"); 
}); 
}); 
$(this).click(function() { 
var dataType = $(this).attr("type"); 
checkColumnValue(thisIndex, dataType); 
}); 
}); 
$("tbody tr").removeClass();//先移除tbody下tr的所有css类 
$("tbody tr").mouseover(function(){ 
$(this).addClass("hover"); 
}).mouseout(function(){ 
$(this).removeClass("hover"); 
}); 
//对表格排序 
function checkColumnValue(index, type) { 
var trsValue = new Array(); 
tbBodyTr.each(function() { 
var tds = $(this).find(&#39;td&#39;); 
trsValue.push(type + ".separator" + $(tds[index]).html() + ".separator" + $(this).html()); 
$(this).html(""); 
}); 
var len = trsValue.length; 
if(index == sortIndex){ 
trsValue.reverse(); 
} else { 
for(var i = 0; i < len; i++){ 
type = trsValue[i].split(".separator")[0]; 
for(var j = i + 1; j < len; j++){ 
value1 = trsValue[i].split(".separator")[1]; 
value2 = trsValue[j].split(".separator")[1]; 
if(type == "number"){ 
value1 = value1 == "" ? 0 : value1; 
value2 = value2 == "" ? 0 : value2; 
if(parseFloat(value1) > parseFloat(value2)){ 
var temp = trsValue[j]; 
trsValue[j] = trsValue[i]; 
trsValue[i] = temp; 
} 
} else if(type == "ip"){ 
if(ip2int(value1) > ip2int(value2)){ 
var temp = trsValue[j]; 
trsValue[j] = trsValue[i]; 
trsValue[i] = temp; 
} 
} else { 
if (value1.localeCompare(value2) > 0) {//该方法不兼容谷歌浏览器 
var temp = trsValue[j]; 
trsValue[j] = trsValue[i]; 
trsValue[i] = temp; 
} 
} 
} 
} 
} 
for(var i = 0; i < len; i++){ 
$("tbody tr:eq(" + i + ")").html(trsValue[i].split(".separator")[2]); 
} 
sortIndex = index; 
} 
//IP转成整型 
function ip2int(ip){ 
var num = 0; 
ip = ip.split("."); 
num = Number(ip[0]) * 256 * 256 * 256 + Number(ip[1]) * 256 * 256 + Number(ip[2]) * 256 + Number(ip[3]); 
return num; 
} 
})
Running result:


Jquery operates table columns and sorts tables

I believe you have mastered the method after reading the case in this article, and more How exciting, please pay attention to other related articles on php Chinese website!

Recommended reading:

Detailed explanation of JS JQuery dynamic operation table row method

Detailed explanation of JSON.parse() and JSON. The difference and usage of stringify()

The above is the detailed content of Jquery operates table columns and sorts tables. For more information, please follow other related articles on the PHP Chinese website!

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