Split a “big” table to smaller tables

前端 未结 4 1787
走了就别回头了
走了就别回头了 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:42

    I made better version of table split function that support fix columns (repeat in all tables) and it waste a lot of time:

    function range(start, end) {
      var array = new Array();
      for (var i = start; i <= end; i++) {
        array.push(i);
      }
      return array;
    }
    
    function splitTables($tables, chunkSize, fixCols) {
      $table = $($tables);
      console.log('fixCols :', fixCols);
      fixCols = fixCols || [];
      console.log('fixCols :', fixCols);
      fixCols = fixCols.sort();
      console.log('fixCols :', fixCols);
      //chunkSize -= fixCols.length;
      var rowLength = $('tr:first>*', $table).length;
      console.log('total length:', rowLength);
      var n = Math.ceil(rowLength / chunkSize);
      var bufferTables = [];
      var numberList = range(1, rowLength);
    
      for (var i = 1; i <= n; i++) {
        var colList = fixCols.slice(0);
        //console.log('fixCols :',fixCols);
        //console.log('colList :',colList);
        console.log('numberList :', numberList);
        while (colList.length < chunkSize && numberList.length > 0) {
          var index = numberList.shift();
          console.log(index, colList);
          if (colList.indexOf(index) == -1) {
            colList.push(index);
          }
        }
    
        console.log('col list:', colList);
        var $newTable = $table.clone(true)
        for (var index = 1;
          (index <= rowLength); index++) {
          if (colList.indexOf(index) == -1) {
            console.log('removing:', index);
            $('tr>:nth-child(' + index + ')', $newTable).hide();
          }
        }
        bufferTables.push($newTable)
      }
    
      $(bufferTables.reverse()).each(function(i, $el) {
        $('
    ').insertAfter($table); $el.insertAfter($table); }); $table.remove(); } $(function() { $('#sbtn').click(function() { splitTables($("#tb"), 3, [1]); }); })
    
    
    
    
    0 1 2 3 4 5 6
    Sum $180 $500 $300 $700 $600 $1000
    Home $100 $200 $200 $300 $400 $500
    Work $80 $300 $100 $400 $200 $500

提交回复
热议问题