jQuery:在Web页面实现表格排序功能

用jQuery实现表格排序

  • 参考:
    方法一:https://blog.csdn.net/wdfscp/article/details/8373311
    方法二:https://blog.csdn.net/wdfscp/article/details/8373391
    方法一和方法二差不多,主要是排序函数的设置不一样
    本文参考方法一
  • 思路
    ①鼠标在表头按下,获取表头的列值,index
    var thisIndex = tbHeadTh.index($(this)); //获取th所在的列号
    ~
    ②创建arrayarray var trsValue = new Array();
    ~
    each遍历每一行,push进array
    ~
    ④放入某个数组的string分为三个部分,(type,记录string还是int)(作为排序依据的该行的目的单元格元素,在该行内通过 之前获取的index 进行索引)(该行全部内容),这三个部分用标记符separator隔开,方便之后的分割,关键代码如下:
    trsValue.push(type + ".separator" + $(tds[index]).html() + ".separator" + $(this).html());
    ~
    ⑤根据每一行的分割内容进行排序(这里采用的是冒泡排序)
    首先获取type,方便不同类型的排序type = trsValue[i].split(".separator")[0];
    获取排序依据单元格value1 = trsValue[i].split(".separator")[1];
    数字类:parseFloat
    string类:localeCompare
    排序过程中:trsValue[j] = trsValue[i];进行整行的交换数据(把type、排序依据的单元格、整行数据)
    ~
    ⑥最后按行输出$("tbody tr:eq(" + i + ")").html(trsValue[i].split(".separator")[2]);
    ~
    ⑦表格内变色效果,通过mouseoveraddClass("hover")removeClass("hover")
    ~
  • 完整代码如下
    (如果想css、html、js分开看,可以看原链接)
    (代码中标记了自己理解的注释)
<!DOCTYPE html>
<html>
	<head>
        <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
            
        <style type="text/css">
                div
                {
                    width: 1024px;
                    margin: 0 auto; /*div相对屏幕左右居中*/
                }
                table
                {
                    border: solid 1px #666;
                    border-collapse: collapse;
                    width: 100%;
                    cursor: default; /*该属性定义了鼠标指针放在一个元素边界范围内时所用的光标形状,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>
		<div>
        <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" οnclick="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>
    </div>
   
   <script type="text/javascript">
        $(function () {
            var tableObject = $('#tableSort'); //获取id为tableSort的table对象
            var tbHead = tableObject.children('thead'); //获取table对象下的thead
            var tbHeadTh = tbHead.find('tr th'); //获取thead下的tr下的th
            var tbBody = tableObject.children('tbody'); //获取table对象下的tbody
            var tbBodyTr = tbBody.find('tr'); //获取tbody下的tr
 
            var sortIndex = -1;
 
            tbHeadTh.each(function () {//遍历thead的tr下的th
                var thisIndex = tbHeadTh.index($(this)); //获取th所在的列号
                //给表态th增加鼠标位于上方时发生的事件
                $(this).mouseover(function () {
                    tbBodyTr.each(function () {//编列tbody下的tr
                        var tds = $(this).find("td"); //获取列号为参数index的td对象集合
                        $(tds[thisIndex]).addClass("hover");//给列号为参数index的td对象添加样式
                    });
                }).mouseout(function () {//给表头th增加鼠标离开时的事件
                    tbBodyTr.each(function () {
                        var tds = $(this).find("td");
                        $(tds[thisIndex]).removeClass("hover");//鼠标离开时移除td对象上的样式
                    });
                });
 
                $(this).click(function () {//给当前表头th增加点击事件
                    var dataType = $(this).attr("type");//点击时获取当前th的type属性值
                    checkColumnValue(thisIndex, dataType);
                });
            });
 
            $("tbody tr").removeClass(); //先移除tbody下tr的所有css类
            //table中tbody中tr鼠标位于上面时添加颜色,离开时移除颜色
            $("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('td');
                    //获取行号为index列的某一行的单元格内容与该单元格所在行的行内容添加到数组trsValue中
                    //index是形参,实参是th所在的列号thisIndex
                    //gu理解:类似爬虫的正则化,以获取其中内容
                    //gu理解:感觉这是一种字符串的写法,之后指定这是按照.separator进行分割 
                    //gu理解:以array形式存储,每次push进新元素,新元素是string
                    //gu理解:分割开获取的东西分别是 type(string/numbei/ip)、这一列的该行元素、该行所有内容                 
                    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++) {
                        //split() 方法用于把一个字符串分割成字符串数组
                        //获取每行分割后数组的第一个值,即此列的数组类型,定义了字符串\数字\Ip
                        //gu理解:之前以.separator存储,现在以此分割
                        //gu理解:IP应该是该行所有内容
                        //gu理解:i是遍历所以行(每行存储在一个array里)、[0]应该是指截取出来的第一个元素
                        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") {
                                //gu:若为空,则对其赋值为0,方便排序
                                value1 = value1 == "" ? 0 : value1;
                                value2 = value2 == "" ? 0 : value2;
                                //gu:parseFloat将原来以string放入的内容解析为数字
                                if (parseFloat(value1) > parseFloat(value2)) {
                                    var temp = trsValue[j];
                                    trsValue[j] = trsValue[i];
                                    trsValue[i] = temp;
                                }
                            } else if (type == "ip") {
                                //gu:ip2int函数在下方定义,是一个
                                if (ip2int(value1) > ip2int(value2)) {
                                    var temp = trsValue[j];
                                    trsValue[j] = trsValue[i];
                                    trsValue[i] = temp;
                                }
                            } else {
                                //gu:当type为string时
                                if (value1.localeCompare(value2) > 0) {//该方法不兼容谷歌浏览器
                                    var temp = trsValue[j];
                                    trsValue[j] = trsValue[i];
                                    trsValue[i] = temp;
                                }
                            }
                        }
                    }
                }
 
                //gu:之前len记录了向trsValue push进多少东西
                for (var i = 0; i < len; i++) {
                    //gu:tbody下 第i+1 个 tr (因为i是从0开始的,即index=i)
                    //gu:指定其中的内容用 分割 后的第二个内容代替(即该行全部内容)
                    //gu:排序过程中 trsValue[j] = trsValue[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;
            }
 
        })
    </script>

	</body>

</html>

详解

行245

jQuery each() 方法

each() 方法为每个匹配元素规定要运行的函数。

语法:
$(selector).each(function(index,element))

function(index,element)	必需。为每个匹配元素规定运行的函数。
index - 选择器的 index 位置。
element - 当前的元素(也可使用 "this" 选择器)。
Example1:
$("li").each(function(){
	 alert($(this).text())
});


Example2:
tbBodyTr.each(function () {//编列tbody下的tr
    var tds = $(this).find("td"); //获取列号为参数index的td对象集合
    $(tds[thisIndex]).addClass("hover");//给列号为参数index的td对象添加样式
});

Example3:
tbHeadTh.each(function () {//遍历thead的tr下的th

行246

index

index(),去获取元素的下标
《$ (obj).index(this)与$(this).index()异同讲解》
https://blog.csdn.net/daruanzai3165/article/details/101881941

jquery中的this与 $ (this)的区别总结

(this:html元素)($(this):JQuery对象)
https://blog.csdn.net/weixin_34266504/article/details/93572440

行287

trsValue.push(type + ".separator" + $(tds[index]).html() + ".separator" + $(this).html());

JavaScript push() 方法

push() 方法可向数组的末尾添加一个或多个元素,并返回新的长度。

注意: 新元素将添加在数组的末尾。
注意: 此方法改变数组的长度。
提示: 在数组起始位置添加元素请使用 unshift() 方法。
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi")

jQuery html() 方法

html() 方法设置或返回被选元素的内容(innerHTML)。

当该方法用于返回内容时,则返回第一个匹配元素的内容。
当该方法用于设置内容时,则重写所有匹配元素的内容。
提示:如只需设置或返回被选元素的文本内容,请使用 text() 方法。
返回内容:
$(selector).html()

设置内容:
$(selector).html(content)

使用函数设置内容:
$(selector).html(function(index,currentcontent))
$(this).html("");
清空该元素的html内容
如果不加的话,每弹出一次对话框。里面的提示内容会重复增加,
加上的作用就是为了清除当前元素的内容

行303

type = trsValue[i].split(".separator")[0];

JavaScript split() 方法

split() 方法用于把一个字符串分割成字符串数组

语法
stringObject.split(separator,howmany)

参数
separator  必需。字符串或正则表达式,从该参数指定的地方分割 stringObject。
howmany	   可选。该参数可指定返回的数组的最大长度。
           如果设置了该参数,返回的子串不会多于这个参数指定的数组。
           如果没有设置该参数,整个字符串都会被分割,不考虑它的长度。

提示:
如果把空字符串 ("") 用作 separator,那么 stringObject 中的每个字符之间都会被分割。
Example1:
把单词分割为字母,或者把字符串分割为字符:
"hello".split("")	//可返回 ["h", "e", "l", "l", "o"]
若只需要返回一部分字符,可使用 howmany 参数:
"hello".split("", 3)	//可返回 ["h", "e", "l"]

Example2:
var str="How are you doing today?"
str.split(" ")//返回:How,are,you,doing,today?
str.split("")//返回:H,o,w, ,a,r,e, ,y,o,u, ,d,o,i,n,g, ,t,o,d,a,y,?
str.split(" ",3)//返回:How,are,you

Example3:
"2:3:4:5".split(":")	//将返回["2", "3", "4", "5"]
"|a|b|c".split("|")	//将返回["", "a", "b", "c"]

行312

value1 = value1 == "" ? 0 : value1;

js条件运算符

语法:
变量 = (条件) ? 值1:值2

如果条件为 truthy ,则 变量=值1
如果条件为 falsy  ,则 变量=值2

行315

if (parseFloat(value1) > parseFloat(value2)) {

JavaScript parseFloat() 函数

parseFloat() 函数可解析一个字符串,并返回一个浮点数。

语法
parseFloat(string)
Example:
<script type="text/javascript">
	document.write(parseFloat("10")) 
	document.write(parseFloat("10.00")) 
	document.write(parseFloat("10.33")) 
	document.write(parseFloat("34 45 66")) 
	document.write(parseFloat(" 60 ")) 
	document.write(parseFloat("40 years"))
	document.write(parseFloat("He was 40"))
</script>

输出:
10
10
10.33
34
60
40
NaN

行329

if (value1.localeCompare(value2) > 0)

JavaScript localeCompare() 方法

用本地特定的顺序来比较两个字符串。

语法
stringObject.localeCompare(target)

说明
比较结果的数字
如果 stringObject 小于 target,则 localeCompare() 返回小于 0 的数。
如果 stringObject 大于 target,则该方法返回大于 0 的数。
如果两个字符串相等,或根据本地排序规则没有区别,该方法返回 0。

行344

$("tbody tr:eq(" + i + ")").html(trsValue[i].split(".separator")[2]);

jQuery :eq() 选择器

:eq() 选择器选取带有指定 index 值的元素。

index 值从 0 开始,所有第一个元素的 index 值是 0(不是 1)。
经常与其他元素/选择器一起使用,来选择指定的组中特定序号的元素

语法
$(":eq(index)")

例:
$("p:eq(1)").css("background-color","#B2E0FF");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值