Split a “big” table to smaller tables

前端 未结 4 1766
走了就别回头了
走了就别回头了 2021-01-06 09:01

I would like to split a \"big\" table (a lot of columns) to smaller tables every for example 2 columns.

Is there an easy way to do that?

I only have the tab

4条回答
  •  广开言路
    2021-01-06 09:27

    function split($table, chunkSize) {
      var cols = $("th", $table).length - 1;
      var n = cols / chunkSize;
    
      for (var i = 1; i <= n; i++) {
         $("
    ").appendTo("body"); var $newTable = $table.clone().appendTo("body"); for (var j = cols + 1; j > 1; j--) { if (j + chunkSize - 1 <= chunkSize * i || j > chunkSize * i + 1) { $('td:nth-child(' + j + '),th:nth-child(' + j + ')', $newTable).remove(); } } } }

    Where $table is the table jQuery object, and chunkSize is the size of each split. In your example, call it as split($("table"), 2). Note that chunkSize must evenly divide the number of columns (excluding the first one) for this to work correctly, for example, for a table with 7 columns, the valid values for chunkSize are 1, 2, and 3.

    DEMO.

提交回复
热议问题