js 表格排序

文章介绍了两个JavaScript函数,sortrows用于根据指定索引对表格行进行排序,支持自定义排序规则;makeSortable则使表格头部单元格可点击触发对应列的排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 *table:传入的表格
 *n:按tr中的第几个索引进行排序
 *comparator:排序规则,不传按照文本默认的规则进行排序
*/
function sortrows(table, n, comparator) {
    var tbody = table.tBodies[0];
    console.log(tbody);
    var rows = tbody.rows;
    rows = Array.prototype.slice.call(rows,0);
    rows.sort(function (row1, row2) {
        var cell1 = row1.cells[n],
            cell2 = row2.cells[n],
            val1 = cell1.textContent || cell1.innerText,
            val2 = cell2.textContent || cell2.innerText;
        console.log(cell1);
        if(comparator){
            return comparator(val1,val2);
        }
        if(val1 < val2)return -1;
        else if(val1>val2)return 1;
        else return 0;
    });
    rows.forEach(function (v) {
        tbody.appendChild(v);
    });
}

/**
 *table:传入的表格
*/
function makeSortable(table) {
    var ths = table.tHead.rows[0].cells;
    ths = Array.prototype.slice.call(ths,0);
    ths.forEach(function (v,k) {
        v.onclick = function () {
            alert(k);
            sortrows(table,k);
        }
    });

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值