Using jquery to copy a portion of a table in the most optimized way
I am using JQuery to manipulate a page which I do not have access to modify server-side. One of the main things I need to do is create a copy of just a sub-section of one of the tables on the page. More specifically, I need to create 2 tables, one which is a copy of just the first two rows of the table and another which is just the first column.
After optimizing it as far as I could, I'm fairly happy with the performance of the row copy but the column copy is still a bit on the slow side.
I have the following, where sourceTable is the original table and titleColBody is the tbody of a new table created earlier:
sourceTable.find("tr").each(function(){
titleColBody.append(
$("<tr></tr>").append($(this).children(":first").clone())
);
});
On a table with roughly 50 rows and a huge number of columns, this takes approx. 350ms in IE8. Not terrible, but I would like to bring this down a little if possible.
My question is if there is a more efficient way of doing this in JQuery.
Similarly, I create the copy of the first 2 rows of the table as below.
headerTable.find("tbody")
.append(sourceTable.find("tr:eq(0)").clone())
.append(sourceTable.find("tr:eq(1)").clone());
This is fairly quick, however if there is开发者_StackOverflow中文版 a better way of doing it I would be happy to hear it.
Any optimization at all would be greatly appreciated.
Seems like this might be a tad bit faster for the columns, this way you'll only grab one resource set instead of grabbing two sets (one for the TRs and then one for the child TDs):
sourceTable.find("tr > td:first-child").each(function(){
titleColBody.append($("<tr></tr>").append($(this).clone()));
});
Also on another note, if the "titleColBody" is a pointer to a DOM object that causes the browser to have to render the page when it's updated, you're better off appending to a documentFragment and then appending that fragment (so the browser only re-renders once).
For instance:
var titleCol = document.createDocumentFragment();
sourceTable.find("tr > td:first-child").each(function(){
titleCol.append($("<tr></tr>").append($(this).clone()));
});
titleColBody.append(titleCol);
精彩评论