使用jQuery隐藏html表中的空列不起作用:\

    $('table').each(function(a, tbl) { var currentTableRows = $(tbl).attr('rows').length - 1; $(tbl).find('th').each(function(i) { var remove = 0; var currentTable = $(this).parents('table'); var tds = currentTable.find('tr td:nth-child(' + (i + 1) + ')'); tds.each(function(j) { if (this.innerHTML == '') remove++; }); if (remove == currentTableRows) { $(this).hide(); tds.hide(); } }); });    
alaa
Column1Column2Column3Column4
1st1.1
2nd2.1
3rd3.11
4th

这是我的代码……我认为来自库的问题,所以我尝试了很多库,比如jQuery 1.4.4,1.5.2和其他

这是测试,它在那里工作正常http://jsfiddle.net/nlovatt/JsLn8/

但在我的文件..它不起作用..

问候,

您的代码无法正常工作有两个原因。

1)您在加载HEAD立即执行脚本,在此阶段,您的表不存在,因此它什么都不做。 要解决此问题,请确保在页面加载时执行它。

2)当您将列中空白单元格的数量与表格中的总行数进行比较时,您错过了大多数列与表格的行数不同的事实(您的第一行只有一列宽)。 您需要与实际列中的行数进行比较,或者更好的是,只需执行相反的操作并检查非空列。

完整的代码然后变成:

 $(document).ready(function() { $('table').each(function(a, tbl) { $(tbl).find('th').each(function(i) { var remove = true; var currentTable = $(this).parents('table'); var tds = currentTable.find('tr td:nth-child(' + (i + 1) + ')'); tds.each(function(j) { if (this.innerHTML != '') remove = false; }); if (remove) { $(this).hide(); tds.hide(); } }); }); }); 

试试这样吧

  $('#mytable tr th').each(function(i) { //select all td in this column var tds = $(this).parents('table') .find('tr td:nth-child(' + (i + 1) + ')'); //check if all the cells in this column are empty if(tds.length == tds.filter(':empty').length) { //hide header $(this).hide(); //hide cells tds.hide(); } }); 

用于在列中的所有单元格为空时隐藏列中的列