2012-01-11 31 views
2

我必須發送表格的html到html-to-pdf轉換器腳本。我的表必須由來自表1的<thead>,來自表3的<tfoot>和來自表2的<tbody>組成。我用jQuery把html放在一起。這是我有:更有效的方式來建立一個表?

$(document).ready(function() { 
    var html = $('div.dataTables_scroll').html();//so that changes don't affect the main page 
    var h = $(html).find('thead')[0]; 
    var f = $(html).find('tfoot')[1]; 
    var b = $(html).find('tbody')[0]; 
    var newtable = $('<table></table>').append(h, f, b); 
    var d = $('<div></div>').append(newtable); 
    $('#foo').val(d.html()); //to see what the html looks like 
}); 

Here的整個事情的jsfiddle。它工作得不錯,但我認爲應該有一個更優雅的方式。

想法?

+0

屬於上:http://codereview.stackexchange.com/ – 2012-01-11 19:39:14

+0

@Diodeus:代碼審查似乎仍處於測試階段。這可能就是爲什麼我不知道它的存在。 – dnagirl 2012-01-11 19:44:03

回答

2

如何:

var ctx = $('div.dataTables_scroll')[0]; 

var html = [ 
    '<table>', 
     '<thead>' + $('thead', ctx).eq(0).html() + '</thead>', 
     '<tfoot>' + $('tfoot', ctx).eq(1).html() + '</tfoot>', 
     '<tbody>' + $('tbody', ctx).eq(0).html() + '</tbody>', 
    '</table>' 
].join(''); 
0

我不認爲有任何真正的優雅當涉及到構建表。既然你只是建立一張桌子,我建議你堅持你已有的解決方案。但是,如果你需要構建一個由許多行,單元格和其他組成的巨大表格(或多個表格),我建議你這麼做offline;也就是說,將所有的部分組裝成一個普通的字符串緩衝區,並在完成構建後將其插入到DOM中。這樣你就不會通過反覆寫入DOM來減慢瀏覽器的速度,這可能非常昂貴。

+0

你的論據很有道理。但在這種情況下,情況會有所減輕。我從中收穫的表格是DataTables(http://datatables.net/)處理原始表格的輸出。所以要創建一個服務器端版本,我必須基本上覆制DataTable插件,至少部分在服務器端。同樣,服務器腳本需要知道任何用戶應用的修改,如過濾器或排序順序。 – dnagirl 2012-01-11 19:57:05

1

它看起來很穩固。真的,我認爲沒有更高效或優雅的表格工作方式。如果你願意,你可以把它改寫這樣讓它多一點明確:

$(document).ready(function() { 
    var tables = $('div.dataTables_scroll table'); 
    var thead = tables.eq(0).find('thead'); 
    var tfoot = tables.eq(1).find('tfoot'); 
    var tbody = tables.eq(2).find('tbody'); 

    var newTable = $('<table />').append(thead, tfoot, tbody); 
    var result = $('<div />').append(newTable).html(); 

    $('#foo').val(result); 
}); 

我不能說太多關於性能,但它更可讀一點。

0

製作中間表和div是不必要的。寫下信息,放在你想要的地方。不要在中間玩耍。

$(document).ready(function() { 
    var $target = $('div.dataTables_scroll'); 
    var html = "<table><thead>" + $target.find('thead').eq(0).html() + "</thead>"; 
    html += "<tbody>" + $target.find('tfoot').eq(1).html() + "</tbody>"; 
    html += "<tfoot>" + $target.find('tbody').eq(0).html() + "</tfoot></table>"; 
    $('#foo').val(html); 
}); 

jsFiddle

相關問題