2013-04-22 52 views
0

我需要隱藏表中的列,但有涉及rowspans它弄亂了函數。我感謝任何幫助。下面是鏈接,我的代碼:jquery-隱藏列中有rowspans的列

http://jsfiddle.net/SEwVP/73/

下面是函數(在本例中,我試圖隱藏列3):

$('#toggle').click(function(){ 
var lastChilds = $('#tbl td:nth-child(3)'); 
lastChilds.each(function(i){ 
    var rowSpan = $(this).attr('rowspan'); 
    if(rowSpan !== undefined){ 
     lastChilds.splice(i+1, rowSpan-1); 

    } 
    $(this).toggle(); 

    }); 
    }); 

回答

3

我最初是由這個很感興趣因爲它看起來很平凡但實際上令人難以置信。我嘗試了各種方法來解決rowspan s切換正確的單元格。我最初回答昨天,但我很快就刪除了它,因爲我知道它失敗了。

當我們說'第3列'時,並不一定意味着<td>將是該行的第三個孩子,因爲就HTML和rowspan的工作方式而言。

然後是頓悟:表是完美的網格,因此,例如,是所有細胞「視覺感知」作爲第三列共同所有份額的一件事,他們都有着相同的偏移左邊

這是最接近我能得到這麼遠,這也許有點極端的方法基於一個重要的假設就是:沒有colspan s的參與整個表。 (否則,一切都變成糞便)

此演示允許你切換任何列你希望,希望任何行跨度複雜性。

(如果有一個更優雅的解決方案,我一定會想知道我自己)

DEMOhttp://jsfiddle.net/terryyounghk/nGEHW/

$(document).ready(function() { 

    var $table = $('#tbl'); 

    (function scanTable($table) { 

     var $rows = $table.find('tr'), 
      $cells = $table.find('td'), 
      map = {}; 

     // the first row will always have all n columns of cells, 
     // so this is the safest row to collect each columns offset().left 
     $rows.first().find('td').each(function (i, cell) { 
      var $cell = $(cell), 
       left = Math.floor($cell.offset().left); 
      map[left] = i+1; 
      $cell.attr({ 
       'data-nth-col': i+1 
      }); 
     }); 

     // now for the rest of the rows, 
     $rows.not(':first').each(function (i, row) { 
      var $row = $(row), 
       $cells = $row.find('td'); 

      $cells.each(function (j, cell) { 
       var $cell = $(cell), 
        left = Math.floor($cell.offset().left); 
       $cell.attr({ 
        'data-nth-col': map[left] 
       }); 
      }); 
     }); 
    })($table); // scan the entire table ONCE. 
       // We don't want to do this on every toggle 


    $('button[name=toggle]').on('click', function() { 
     var n = +$(this).val(); 
     $table.find('td[data-nth-col='+n+']').toggle(); 
    }); 

});