使用jQuery显示/隐藏表格列

6

我有一张包含五列的表格

column1 column2 column3 column4 column5
------- ------- ------- ------- -------

我有几个复选框,每个复选框对应一列。如果勾选第一个复选框,则需要显示第一列;如果取消勾选,则需要隐藏第一列。其他列同理。

我找到了一些答案,但没有找到解决方案。第一次可以隐藏,但之后的操作都无效。

 $('#tableId td:nth-child(column number)').hide();

请帮我,谢谢提前!


1
如果您能包含一些HTML代码,那就太好了。 - rahularyansharma
如果您正在使用实际的HTML表格,请在您的td上使用类。 - SpYk3HH
什么出了问题?我们能看到代码吗? - Ejaz
我使用了上面的代码。第一次它可以工作。但是从第二次开始就无法工作了。 - PSR
只是提供信息,我更新了我的答案,以便为您充分解释正在发生的事情,并且包含的jsFiddle准确展示了您在工作中所要求的内容。 - SpYk3HH
另外,我给你提供了一个替代的想法,可能有助于实现你的最终目标。这个想法非常简洁。 - SpYk3HH
8个回答

10

以下是完整的解决方案:

http://jsfiddle.net/vXBtP/

并且已经更新为:http://jsfiddle.net/vXBtP/5/

<table>
   <thead>
       <td><input type="checkbox" checked="checked" /></td>
       <td><input type="checkbox" checked="checked" /></td>
       <td><input type="checkbox" checked="checked" /></td>
       <td><input type="checkbox" checked="checked" /></td>
       <td><input type="checkbox" checked="checked" /></td>
    </thead>
    <tbody>
    <tr>
       <td>column 1</td>
        <td>column 2</td>
        <td>column 3</td>
        <td>column 4</td>
        <td>column 5</td>
    </tr>
    </tbody>
</table>

$(document).on('change', 'table thead input', function() {
    var checked = $(this).is(":checked");

    var index = $(this).parent().index();
    if(checked) {
        $('table tbody tr td').eq(index).show();
    } else {
        $('table tbody tr td').eq(index).hide();
    }
});

实际上,我有复选框在表格外面。 - PSR
无论它们在哪里,您只需要将它们放入一个容器中,然后.index()仍然可以工作。因此,即使您将所有<input>放在<div>中,上面的示例仍将起作用。 - Chris Dixon
@Chris 如果表头中有colspan怎么办? - Tushar Sonawane

6
根据您想要隐藏的列号,使用以下这个偷来的一行命令:
$('td:nth-child(2)').hide();

如果你使用th
$('td:nth-child(2),th:nth-child(2)').hide();

我刚刚在你的问题中看到了更多信息,看起来你已经尝试过这个了。你需要像在你的问题中那样指定表格,但这应该可以工作。 - David Houde

3
如果我理解正确的话,您可以使用tr th, tr tdnth-child选择器来简化它。您可以基于索引进行操作,但需要添加1,因为nth-child不像jQuery中的元素那样从0开始索引。而且JS并不需要太详细。我应该提到,在td:nth之前放置非常重要,因为你不希望“仅限于每个n个td”。如果是这种情况,则不会在每一行上隐藏所有列。  

查看工作jsFIDDLE示例

FYI:如果您想要一个“更清晰”的外观(就像turbotax站点上的外观),则不要隐藏td本身。相反,使其略微宽于您最大的文本段,并将每个文本段放置在每个单元格内的

div标记内。然后将您的column选择器更改为抓取每个单元格的inner元素并隐藏它。

在此处查看此替代方式的示例!

HTML

<table>
    <thead>
        <tr>
            <th>
                <input id="chk1" type="checkbox" />
            </th>
            <th>
                <input id="chk1" type="checkbox" />
            </th>
            <th>
                <input id="chk1" type="checkbox" />
            </th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                col1
            </td>
            <td>
                col2
            </td>
            <td>
                col3
            </td>
        </tr>
        <tr>
            <td>
                col1
            </td>
            <td>
                col2
            </td>
            <td>
                col3
            </td>
        </tr>
        <tr>
            <td>
                col1
            </td>
            <td>
                col2
            </td>
            <td>
                col3
            </td>
        </tr>
        <tr>
            <td>
                col1
            </td>
            <td>
                col2
            </td>
            <td>
                col3
            </td>
        </tr>
    </tbody>
</table>
<button>Reset</button>

JavaScript

$(function() {
    //  Selects your table by id, then the input checkboxes inside the table, you can 
    //  alternate this call with classnames on your inputs if you're going to have 
    //  more inputs than what's desired in call here.
        //  also note i'm using the "change" function and not "click", this simply 
        //  provides easier control of what's going on with your inputs and makes 
        //  later calls (like reset) a much easier call. Less thinking required
    $("#tableId input[type=checkbox]").on("change", function(e) {
        //  First variable grabs the inputs PARENT index, this is the TH containing 
        //  the input, thus the column you want hidden.
        //  The second is calling ALL TH's && TD's having that same index number
        var id = $(this).parent().index()+1,
            col = $("table tr th:nth-child("+id+"), table tr td:nth-child("+id+")");
        //  This simple inline "if" statement checks if the input is checked or now
        //  and shows the columns based on if it IS checked
        $(this).is(":checked") ? col.show() : col.hide();
    }).prop("checked", true).change(); // here i set all inputs to checked without having to write it in the above HTML

    $("button").on("click", function(e) {
        $("input[type=checkbox]").prop("checked", true).change();
    });
})

2
您可以获取表格的标题索引并隐藏表格的标题和td元素。就像这样:
假设表头的索引是 index = 2;
var index= tableHeaderIndex; // 2 here

$('th:nth-child('+index+')').hide();
$('td:nth-child('+index+')').hide();

2

这样吗?

快速搭建但应该可以使用。

<table id="TabToHide">
    <tr>
        <td class="Col1">Col 1</td>
        <td class="Col2">Col 2</td>
        <td class="Col3">Col 3</td>
        <td class="Col4">Col 4</td>
        <td class="Col5">Col 5</td>
    </tr>
    <tr>
        <td class="Col1">Stuff 1</td>
        <td class="Col2">Stuff 2</td>
        <td class="Col3">Stuff 3</td>
        <td class="Col4">Stuff 4</td>
        <td class="Col5">Stuff 5</td>
    </tr>    
</table>

<br />

<table>
    <tr>
        <td><input name="Col1" type="checkbox" checked="checked" /></td>
        <td><input name="Col2" type="checkbox" checked="checked" /></td>
        <td><input name="Col3" type="checkbox" checked="checked" /></td>
        <td><input name="Col4" type="checkbox" checked="checked" /></td>
        <td><input name="Col5" type="checkbox" checked="checked" /></td>
    </tr>
</table>

Javascript

   $('input:checkbox').change(function(){
   var ColToHide = $(this).attr("name");    
    if(this.checked){
        $("td[class='" + ColToHide + "']").show();        
    }else{
        $("td[class='" + ColToHide + "']").hide();
    }

    $('div#Debug').text("hiding " + ColToHide);
});

1
 $(document).ready(function(){
    $('table tr input:checkbox').change(function(){
        var num = $(this).parents("th").index(); 
        alert(num);
        if($(this).is(":checked"))
        {

            $('table tbody tr td').eq(num).show();   
        }else
        {
            $('table tbody tr td').eq(num).hide(); 
        }

    });
});

JS FIDDLE LINK

{{链接1:JS FIDDLE 链接}}


0
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Show and Hide Columns in a Table</title>
    <link href="CSS/table.css" rel="stylesheet" />
    <script src="scripts/jquery-1.11.1.min.js"></script>
    <script>
        $(function () {
            var $chk = $("#grpChkBox input:checkbox");
            var $tbl = $("#someTable");
            $chk.prop('checked', true);
            $chk.click(function () {
                var colToHide = $tbl.find("." + $(this).attr("name"));
                $(colToHide).toggle();
            });
        });
    </script>
</head>
<body>
    <h2>Show and Hide Columns in a Table</h2>
    <p>Click on each Checkbox to hide corresponding Column</p>
    <div id="grpChkBox">
        <p><input type="checkbox" name="empid" /> Employee ID</p>
        <p><input type="checkbox" name="fname" /> First Name</p>
        <p><input type="checkbox" name="lname" /> Last Name</p>
        <p><input type="checkbox" name="email" /> Email</p>
        <p><input type="checkbox" name="phone" /> Phone</p>
    </div>

    <table id="someTable">
        <thead>
            <tr>
                <th class="empid">EmpId</th>
                <th class="fname">First Name</th>
                <th class="lname">Last Name</th>
                <th class="email">Email</th>
                <th class="phone">Phone</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td class="empid">E342</td>
                <td class="fname">Bill</td>
                <td class="lname">Evans</td>
                <td class="email">Bill@devcurry.com</td>
                <td class="phone">234-2345-2345</td>
            </tr>
            <tr>
                <td class="empid">E343</td>
                <td class="fname">Laura</td>
                <td class="lname">Matt</td>
                <td class="email">laura@devcurry.com</td>
                <td class="phone">123-1234-5678</td>
            </tr>
            <tr>
                <td class="empid">E344</td>
                <td class="fname">Ram</td>
                <td class="lname">Kumar</td>
                <td class="email">ram@devcurry.com</td>
                <td class="phone">345-3456-7890</td>
            </tr>
        </tbody>
    </table>

</body>
</html>

0
你可以在你的“th”元素上添加一个“id”,然后简单地调用: $('#yourId').hide();
这是我使用的代码:
$(document).on('click', '.form-check-input', function(e){
  var finition_checked =  $('#finition_select[type="checkbox"]:checked').map(function(){
    return $(this).prop('checked');
  }).get();
  var size_checked = $('#size_select[type="checkbox"]:checked').map(function(){
    return $(this).prop('checked');
  }).get();
  if (finition_checked && size_checked.length === 0){
    $('#price-container').hide();
    $('.table-responsive').show();
    $('#col_size').hide();
  };
  if (finition_checked.length === 0 && size_checked){
    $('#price-container').hide();
    $('.table-responsive').show();
    $('#col_finition').hide();
  };
  if(size_checked && finition_checked){
    $('#price-container').hide();
    $('.table-responsive').show();
  }
  if(size_checked.length === 0 && finition_checked.length === 0){
    $('#price-container').show();
    $('.table-responsive').hide();
  };
  console.log(finition_checked, size_checked)
  var unique_value = [];
  var finition = [];
  var size = [];
  //more logic to come


});


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接