更有效的方法来建立一个表?

时间:2012-01-11 19:36:13

标签: jquery jquery-selectors

我必须将表格的html发送到html-to-pdf转换器脚本。我的表必须由table1的<thead>,table3的<tfoot>和table2的<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。它运作良好,但我认为应该有一个更优雅的方式。

想法?

4 个答案:

答案 0 :(得分: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( '' );

答案 1 :(得分: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);
});

我不能说性能,但它更具可读性。

答案 2 :(得分:0)

在构建表格时,我认为没有任何真正的优雅。由于您只是构建一个表,我建议您坚持使用现有的解决方案。

但是,如果你需要构建一个由许多行,单元格等组成的巨大的表(或多个表),我建议你这样做离线;也就是说,将所有部件组装成一个普通的字符串缓冲区,并在完成构建后将其插入DOM中。这样你就不会通过反复写入DOM来减慢浏览器的速度,这可能非常昂贵。

答案 3 :(得分: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

相关问题