我有一张下列表格:
<table id="mytable" width="500" border="1" cellspacing="0" cellpadding="0"> <thead> <tr> <th><span>1</th><th><span>2</th><th><span>3</th> </tr> </thead> <tbody> <tr> <td><span>1/span></td> <td><span></span></td> <td><span>2/span></td> </tr> <tr> <td><span>1</span></td> <td><span></span></td> <td><span>2</span></td> </tr> <tr> <td><span>1</span></td> <td><span></span></td> <td><span>2</span></td> </tr> </tbody> </table>
我需要做的是 – 隐藏此表的所有列,其中< span>表格单元格包含的元素为空.我将需要完全隐藏单元格,并使用< th>元素在顶部.在我上面的例子中,它是中间列,但可能有很多,不仅仅是一个.
有人可以为此提出建议吗?
提前致谢.
解决方法
这应该工作:
$(document).ready(function() { hideEmptyCols($("#mytable")); }); function hideEmptyCols(table) { //count # of columns var numCols = $("th",table).length; for ( var i=1; i<=numCols; i++ ) { var empty = true; //grab all the <td>'s of the column at i $("td:nth-child(" + i + ")",table).each(function(index,el) { //check if the <span> of this <td> is empty if ( $("span",el).text() != "" ) { empty = false; return false; //break out of each() early } }); if ( empty ) { $("td:nth-child(" + i + ")",table).hide(); //hide <td>'s $("th:nth-child(" + i + ")",table).hide(); //hide header <th> } } }
或者(更简单):
function hideEmptyCols(table) { var rows = $("tr",table).length-1; var numCols = $("th",table).length; for ( var i=1; i<=numCols; i++ ) { if ( $("span:empty",$("td:nth-child(" + i + ")",table)).length == rows ) { $("td:nth-child(" + i + ")",table).hide(); //hide header <th> } } }