如果包含单元格为jQuery,则隐藏表格列 [英] Hiding a table column if the containing cells are empty with jQuery

查看:113
本文介绍了如果包含单元格为jQuery,则隐藏表格列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类型的表:

<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>元素.在上面的示例中,它是中间一列,但可能有很多,而不仅仅是一个.

What I need to do is - hide all the columns of this table where the <span> element contained by the table cell is empty. I will need to hide the cell fully, with the <th> element on the top. In my example above it's the middle column but there may be a lot of them, not only one.

有人可以建议吗?

谢谢.

推荐答案

这应该有效:

$(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 <td>'s
            $("th:nth-child(" + i + ")", table).hide(); //hide header <th>
        }
    }
}

这篇关于如果包含单元格为jQuery,则隐藏表格列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆