Use jQuery to convert table to div's and append th in front of each td

前端 未结 2 1254
醉酒成梦
醉酒成梦 2021-02-10 06:26

I am trying to convert all tables to divs and add the th html or contents of the th in from of each td that is converted to a div.

So my table would look like this:

2条回答
  •  别那么骄傲
    2021-02-10 07:13

    This works:

    $('.content table').replaceWith(function() {
    
        var $th = $(this).find('th'); // get headers
        var th = $th.map(function() {
            return $(this).text();
        }).get(); // and their values
    
        $th.closest('tr').remove(); // then remove them
    
        var $d = $('
    ', { 'class': 'box' }); $('tr', this).each(function(i, el) { var $div = $('
    ', {'class': 'inner'}).appendTo($d); $('td', this).each(function(j, el) { var n = j + 1; var $row = $('
    ', { 'class': 'row-' + n }); $row.append( $('', { 'class': 'label-' + n, text: th[j] }), ' : ', $('', { 'class': 'data-' + n, text: $(this).text() })).appendTo($div); }); }); return $d; });

    demo at http://jsfiddle.net/alnitak/UK395/

提交回复
热议问题