如何对知道行位置的表进行排序?

时间:2012-09-03 10:01:18

标签: javascript

我有一张桌子:

<table>
    <tr><td>1</td></tr>
    <tr><td>2</td></tr>
    <tr><td>3</td></tr>
</table>

一个数组,告诉每一行应该到哪里[{index: 2},{index: 1},{index: 0}](第一行是数组中的最后一行,第二行是数组中的1和数组中的第三行0

1 个答案:

答案 0 :(得分:0)

这是我的方法。

// create a new temporary tbody outside the DOM (similar to jQuery's detach)
var tbody_tmp   = document.createElement('tbody');

// itterate through the array in the order of a new table
for(var i = 0, j = data.length; i < j; i++)
{
    // make a copy of current row (otherwise, append child removes the row from the rows array and messes up the index-finder; there got be a better way for this)
    var row     = rows[data[i].index].cloneNode(true);

    tbody_tmp.appendChild(row);

    // reset the index to reflect the new table order (optional, outside the sample)
    data[i].index   = i;
}

// Note that tbody is a jquery object
tbody.parent()[0].replaceChild(tbody_tmp, tbody[0]);

尽管如此,克隆方法很慢。拥有10,000多条记录需要大约1200毫秒。此外,最好采用无jQuery方法。

发布此信息以防其他人发现其需求足够简单(少于1,000行)。


经过几个小时的不安思考,我最终得到了以下内容。如果这个样本还不够,我写了一篇完整的博客文章,解释其背后的逻辑,http://anuary.com/57/sorting-large-tables-with-javascript

// Will use this to re-attach the tbody object.
var table       = tbody.parent();

// Detach the tbody to prevent unnecessary overhead related
// to the browser environment.
var tbody       = tbody.detach();

// Convert NodeList into an array.
rows            = Array.prototype.slice.call(rows, 0);

var last_row    = rows[data[data.length-1].index];

// Knowing the last element in the table, move all the elements behind it
// in the order they appear in the data map
for(var i = 0, j = data.length-1; i < j; i++)
{
    tbody[0].insertBefore(rows[data[i].index], last_row);

    // Restore the index.
    data[i].index   = i;
}

// Restore the index.
data[data.length-1].index   = data.length-1;

table.append(tbody);