2

我读过 createDocumentFragment 比在 for 循环中将元素一个一个地附加到 DOM 快得多,例如,请参见此处

我想做的事:

  1. 在文档片段中创建表格列。此列应包含数组中的数字(例如“评级”)。
  2. 之后,我想用新列(“片段”列)替换现有列。所以我可以一次将整个列放到 DOM 中。

我的问题:

如果已经有一个列,我真的不知道如何替换现有列。另一方面,附加是没有问题的。

我的 JSfiddle:http: //jsfiddle.net/LEqG9/2/

有用的链接,这里这里

HTML

<table id = "table">
    <tr>
        <th>Name</th>
        <th>Rating</th>
    </tr>
    <tr>
        <td>A.H.Hattray </td>
        <td id = "row0"></td>
    </tr>
    <tr>
        <td>Icke_eben </td>
        <td id = "row1"></td>
    </tr>
    <tr>
        <td>John_Doe123 </td>
        <td id = "row2"></td>
    </tr>
</table>

Javascript

var rating = [1, 10, 3];
var fragment = document.createDocumentFragment();


for (var i = 0, len = rating.length; i < len; i++){ 
    var element = document.createElement('tr');
    element.innerHTML = rating[i];
    fragment.appendChild(element);
}
document.getElementById('table').appendChild(fragment); //I know here should be the code to replace the second column!
4

2 回答 2

2

Columns can't be put into the table all at once (and thus won't work as a fragment) because a column is a bunch of different cells in each of a whole bunch of rows - it's not an entity by itself.

One thing you could do for good performance is to temporarily hide the table with display: none, add all your rows/cells and then show the table again. This should allow the browser to avoid intermediate layout issues every time you add a new cell and you should only get one repaint with the final content.

于 2014-05-29T21:08:39.837 回答
2

The following code demonstrates that it is possible to manipulate an existing table in a DocumentFragment.

var rating = [1, 10, 3];
var theTable = document.getElementById('table');
var frag = document.createDocumentFragment();
frag.appendChild(theTable);
var col2 = frag.querySelectorAll('tr td:nth-of-type(2)');
for (var i=0; i < col2.length; i++) {
    col2[i].innerHTML = rating[i];
}
// it is also possible to use insertCell and deleteCell
var theRows = frag.querySelectorAll('tr');
for (var i=0; i < theRows.length; i++) {
    var x = theRows[i].insertCell(1);
    if (i > 0) 
        x.innerHTML = 'new one';
    else
        x.innerHTML = 'The Header';
}
document.body.appendChild(frag);

(Making the new cell in the first row a TH element, rather than TD requires a little more work, using createElement and appendChild or insertBefore.)

If you step through this the table is removed from the DOM when appended to the fragment, then reappears when the fragment is appended to the body.

于 2014-05-29T21:57:25.613 回答