jquery - 在 jQuery 中对行进行排序的最佳方法是什么?

标签 jquery sorting

我有一个像这样的TR(或div,它不重要)

我想按SCORE 对行进行排序。

Name     |     Age        |Score 
-----------------------------------
John           26           90
paul           25           75
ringo          25           77

知道已经有一个jquery插件可以对进行排序,但我想构建我的自己的插件。

我在分数列中查找值没有问题 - 这很简单。

我的问题是如何排序和显示新结果?我想到了一些事情

1) take all the tr's elements to array of jQuery elements .

2) by .each sort the array

3) delete the old content

4)by .each loop - 'append' each TR by the order of the appearence in the array.

有更好的方法吗?

最佳答案

我之前编写过一种用于对表进行排序的有效算法 ( answer )。我针对这种情况调整了函数:

function sortTable(){
    var tbl = document.getElementById("myTable").tBodies[0];
    var store = [];
    for(var i=0, len=tbl.rows.length; i<len; i++){
        var row = tbl.rows[i];
        var sortnr = parseFloat(row.cells[2].textContent || row.cells[2].innerText);
        if(!isNaN(sortnr)) store.push([sortnr, row]);
    }
    store.sort(function(x,y){
        return x[0] - y[0];
    });
    for(var i=0, len=store.length; i<len; i++){
        tbl.appendChild(store[i][1]);
    }
    store = null;
}

要对表进行排序,请使用 `sortTable();

代码说明:

  1. 创建了两个变量:HTMLTableSectionElement tblArray store
  2. 循环遍历 tBody 的所有元素(=行),并将一个新数组推送到 store 中,该数组由两个元素组成:[sortnr, row]
    sortnr 保存该行第二个单元格的数值,用于排序功能(向前查看)
    row 是对 HTMLTableRowElement 的引用,稍后用于移动行。
  3. store.sort(..) 根据 sortnr 对数组 store 进行排序(如上面所定义,本说明的#2)。
  4. 循环遍历已排序的数组,并将行附加到表的末尾(tbl.appendChild 将节点从先前的位置移动)

请注意,在第三列(单元格索引 2)处没有有效编号的元素根本不会移动。这些位于表格顶部。

如果您希望无效行位于末尾,请使用:

for(var i=store.length-1; i>=0; i--){
    tbl.insertBefore(store[i][1], tbl.rows[0]);
}

Royi Namir 提出的问题(评论)

youre the man. just one more question : you wrote 'tbl.appendChild moves the node from the previous location' , and i thoguth to my self that the action is appendChild - but behind the scenes it moves(!) the element. I read about it and they said that if its the same object then it moved. but how dows he knows that its the same object? he doesnt have any ID or something to recognize ...

答案:
(现实生活中的例子:)假设,你看到一个苹果放在 table 上。如果你想让同一个苹果在地板上,你会怎么做? 拿起苹果并将其放在地板上

这同样适用于appendChild:当您请求追加节点时,脚本引擎希望将要放置的节点放入树中。因此,前一个节点将被删除,因为 » appendChild 不会复制节点。 <
为了复制节点,存在函数element.cloneNode()

关于jquery - 在 jQuery 中对行进行排序的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7570445/

相关文章:

javascript - @符号在这里是什么意思

MySQL + PHP 按组合字符串排序

python - `sorted(list)` 与 `list.sort()` 有什么区别?

javascript - 为什么jQuery或诸如getElementById之类的DOM方法找不到元素?

javascript - 禁用移动设备中的默认保存图像选项

javascript - 在多个域之间共享一个 JavaScript 文件

javascript - 如何根据其中一个元素对整个元素进行排序?

javascript - 使用 Split 函数对 Javascript 数组进行排序

java - java Collection.sort() 的内存消耗

javascript - jQuery UI 可放置类