search
HomeWeb Front-endJS TutorialPlug-in for merging the same cells in a table based on jquery (lite version)_jquery

效果如下

原表格:

col0 col1 col2 col3
SuZhou 11111 22222 SuZhouCity
SuZhou 33333 44444 SuZhouCity
SuZhou 55555 66666 SuZhouCity
ShangHai 77777 88888 ShangHaiCity
ShangHai uuuuu hhhhh ShangHaiCity
ShangHai ggggg ccccc ShangHaiCity
GuangZhou ttttt eeeee GuangZhouCity
GuangZhou ppppp qqqqq GuangZhouCity

处理之后的样子:

col0 col1 col2 col3
SuZhou 11111 22222 SuZhouCity
33333 44444
55555 66666
ShangHai 77777 88888 ShangHaiCity
uuuuu hhhhh
ggggg ccccc
GuangZhou ttttt eeeee GuangZhouCity
ppppp qqqqq

效果出来, 看上去比较简单, 下面先看下页面

复制代码 代码如下:




























































col0 col1 col2 col3
SuZhou 11111 22222 SuZhouCity
SuZhou 33333 44444 SuZhouCity
SuZhou 55555 66666 SuZhouCity
ShangHai 77777 88888 ShangHaiCity
ShangHai uuuuu hhhhh ShangHaiCity
ShangHai ggggg ccccc ShangHaiCity
GuangZhou ttttt eeeee GuangZhouCity
GuangZhou ppppp qqqqq GuangZhouCity


核心代码:
复制代码 代码如下:

// 这里写成了一个jquery插件的形式
$('#process').mergeCell({
// 目前只有cols这么一个配置项, 用数组表示列的索引,从0开始
// 然后根据指定列来处理(合并)相同内容单元格
cols: [0, 3]
});

下面看看这个小插件的完整代码:
复制代码 代码如下:

;(function($) {
// After looking at the jquery source code, you can find that $.fn is $.prototype, jQuery is only retained for compatibility with earlier versions of the plug-in
// The form of prototype
$.fn.mergeCell = function(options) {
return this.each(function() {
var cols = options.cols;
for ( var i = cols.length - 1; cols[i] != undefined; i--) {
// fixbug console debugging
// console.debug(cols[i]);
mergeCell($(this), cols [i]);
}
dispose($(this));
});
};
// If you have a clear understanding of the concepts of closure and scope in JavaScript, this is a plug-in Private methods used internally
// For details, please refer to the book introduced in my previous essay
function mergeCell($table, colIndex) {
$table.data('col-content', ''); // Store cell content
$table.data('col-rowspan', 1); // Store calculated rowspan value, which defaults to 1
$table.data('col-td' , $()); // Store the first td found that is different from the previous row (encapsulated by jQuery), defaulting to an "empty" jquery object
$table.data('trNum', $( 'tbody tr', $table).length); //The total number of rows of the table to be processed, used for judgment when the last row is subjected to special processing
//The key is to "scan" each row of data. It is to locate col-td, and its corresponding rowspan
$('tbody tr', $table).each(function(index) {
// colIndex in td:eq is the column index
var $td = $('td:eq(' colIndex ')', this);
// Get the current content of the cell
var currentContent = $td.html();
// First Take this branch the next time
if ($table.data('col-content') == '') {
$table.data('col-content', currentContent);
$table. data('col-td', $td);
} else {
// The previous row has the same content as the current row
if ($table.data('col-content') == currentContent) {
// If the content of the previous row is the same as the current row, col-rowspan is accumulated and the new value is saved
var rowspan = $table.data('col-rowspan') 1;
$table.data(' col-rowspan', rowspan);
// It is worth noting that if $td.remove() is used, it will affect the processing of other columns
$td.hide();
// The situation in the last line is a bit special
// For example, the contents of the td in the last two lines are the same, then the td saved in col-td at this time should be set to rowspan in the last line
if ( index = = $table.data('trNum'))
$table.data('col-td').attr('rowspan', $table.data('col-rowspan'));
} else { // The content of the previous row is different from the current row
// col-rowspan defaults to 1, if the calculated col-rowspan has not changed, it will not be processed
if ($table.data('col-rowspan') != 1) {
$table.data('col-td').attr('rowspan', $table.data('col-rowspan'));
}
// Save the first Once a td with different content appears, and its content, reset col-rowspan
$table.data('col-td', $td);
$table.data('col-content', $ td.html());
$table.data('col-rowspan', 1);
}
}
});
}
// also private Function to clean up memory
function dispose($table) {
$table.removeData();
}
})(jQuery);

Main instructions It should be all in the comments. The code is indeed relatively simple, but some areas still deserve improvement
•The table content to be processed is searched starting from tbody. If there is no tbody, a more general solution should be given
•for ( var i = cols.length - 1; cols[i] != undefined; i--)... If the amount of table data is large and there are many columns processed, failure to optimize here will cause browser problems For the risk of thread blocking, you can consider using setTimeout
• There are many other things worth improving, I think there should be a lot
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
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor