2013-04-22 50 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(); 
    }); 

});