我有一张下列表格:
<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> } } }
原文地址:https://www.jb51.cc/jquery/181307.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。