0

我有一张桌子:

<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是数组)。

4

1 回答 1

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);
于 2012-09-03T10:02:41.063 回答