简体   繁体   English

如何从表头(th)中获取相应的表列(td)?

[英]How can I get the corresponding table column (td) from a table header (th)?

I want to get the entire column of a table header. 我想得到表头的整个列。

For example, I want to select the table header "Address" to hide the address column, and select the "Phone" header to show the correspondent column. 例如,我想选择表头“Address”来隐藏地址列,并选择“Phone”标题来显示对应列。

<table>
<thead> 
    <tr>
        <th id="name">Name</th>
        <th id="address">Address</th>
        <th id="address" class='hidden'>Address</th>
    </tr>
</thead> 
<tbody>
    <tr>
        <td>Freddy</td>
        <td>Nightmare Street</td>
        <td class='hidden'>123</td>
    </tr>
    <tr>
        <td>Luis</td>
        <td>Lost Street</td>
        <td class='hidden'>3456</td>
    </tr>
</tbody>

I want to do something like http://www.google.com/finance?q=apl (see the related companies table) (click the "add or remove columns" link) 我想做一些像http://www.google.com/finance?q=apl (参见相关公司表) (点击“添加或删除列”链接)

Something like this would work - 像这样的东西会起作用 -

$('th').click(function() {
    var index = $(this).index()+1;
    $('table td:nth-child(' + index + '),table th:nth-child(' + index + ')').hide()
});

The code above will hide the relevant column if you click on the header, the logic could be changed to suit your requirements though. 如果单击标题,上面的代码将隐藏相关列,但逻辑可以根据您的要求进行更改。

Demo - http://jsfiddle.net/LUDWQ/ 演示 - http://jsfiddle.net/LUDWQ/

With a couple simple modifications to your HTML, I'd do something like the following (framework-less JS): 通过对HTML的几个简单修改,我会做类似以下的事情(无框架JS):

HTML: HTML:

<input class="chk" type="checkbox" checked="checked" data-index="0">Name</input>
<input class="chk" type="checkbox" checked="checked" data-index="1">Address</input>
<input class="chk" type="checkbox" checked="checked" data-index="2">Phone</input>

<table id="tbl">
<thead> 
    <tr>
        <th>Name</th>
        <th>Address</th>
        <th>Phone</th>
    </tr>
</thead> 
<tbody>
    <tr>
        <td>Freddy</td>
        <td>Nightmare Street</td>
        <td>123</td>
    </tr>
    <tr>
        <td>Luis</td>
        <td>Lost Street</td>
        <td>3456</td>
    </tr>
</tbody>

Javascript: 使用Javascript:

var cb = document.getElementsByClassName("chk");
var cbsz = cb.length;

for(var n = 0; n < cbsz ; ++n) {
    cb[n].onclick = function(e) {
        var idx = e.target.getAttribute("data-index");
        toggleColumn(idx);
    }
}

function toggleColumn(idx) {
    var tbl = document.getElementById("tbl");
    var rows = tbl.getElementsByTagName("tr");
    var sz = rows.length;

    for(var n = 0; n < sz; ++n) {
        var el = n == 0 ? rows[n].getElementsByTagName("th")[idx] : rows[n].getElementsByTagName("td")[idx];
        el.style.display = el.style.display === "none" ? "table-cell" : "none";
    }
}

http://jsfiddle.net/dbrecht/YqUNz/1/ http://jsfiddle.net/dbrecht/YqUNz/1/

I added the checkboxes as it doesn't make sense to bind the click to the column headers as you won't be able to toggle the visibility, only hide them. 我添加了复选框,因为将点击绑定到列标题没有意义,因为您无法切换可见性,只能隐藏它们。

Simulating the Google Finance show/hide columns functionality: 模拟Google财经显示/隐藏列功能:

http://jsfiddle.net/b9chris/HvA4s/ http://jsfiddle.net/b9chris/HvA4s/

$('#edit').click(function() {
    var headers = $('#table th').map(function() {
        var th =  $(this);
        return {
            text: th.text(),
            shown: th.css('display') != 'none'
        };
    });

    var h = ['<div id=tableEditor><button id=done>Done</button><table><thead><tr>'];
    $.each(headers, function() {
        h.push('<th><input type=checkbox',
               (this.shown ? ' checked ' : ' '),
               '/> ',
               this.text,
               '</th>');
    });
    h.push('</tr></thead></table></div>');
    $('body').append(h.join(''));

    $('#done').click(function() {
        var showHeaders = $('#tableEditor input').map(function() { return this.checked; });
        $.each(showHeaders, function(i, show) {
            var cssIndex = i + 1;
            var tags = $('#table th:nth-child(' + cssIndex + '), #table td:nth-child(' + cssIndex + ')');
            if (show)
                tags.show();
            else
                tags.hide();
        });

        $('#tableEditor').remove();
        return false;
    });

    return false;
});

The easiest way to do this would be to add a class to each td that matches the class of the header. 最简单的方法是为每个匹配标题类的td添加一个类。 When you click the , it checks the class, then hides every td with that class. 单击时,它会检查该类,然后使用该类隐藏每个td。 Since only the s in that column would hide that class, it would effectively hide the column. 由于只有该列中的s会隐藏该类,因此它会有效地隐藏该列。

<table>
  <thead>
    <th>Name</th>
    <th>Address</th>
  </thead>
  <tbody>
    <tr>
       <td class="Name">Joe</td>
       <td class="Address">123 Main St.
  </tbody>
</table>

And the script something like: 脚本类似于:

$('th').click( function() {
  var col = $(this).html(); // Get the content of the <th>
  $('.'+col).hide(); // Hide everything with a class that matches the col value.
});

Something like that, anyway. 无论如何,这样的事情。 That's probably more verbose than it needs to be, but it should demonstrate the principle. 这可能比它需要的更冗长,但它应该证明原理。

Another way would be to simply count how many columns over the in question is, and then loop through each row and hide the td that is also that many columns over. 另一种方法是简单地计算有问题的列数,然后遍历每一行并隐藏也是那么多列的td。 For instance, if you want to hide the Address column and it is column #3 (index 2), then you would loop through each row and hide the third (index 2). 例如,如果要隐藏地址列并且它是列#3(索引2),那么您将遍历每一行并隐藏第三行(索引2)。

Good luck.. 祝好运..

You can do something with CSS, like: 您可以使用CSS执行某些操作,例如:

<html>
<head>
    <style>
        .c1 .c1, .c2 .c2, .c3 .c3{
            display:none;
        }
    </style>
</head>
<body>
<table class="c2 c3">
    <thead> 
        <tr>
            <th id="name" class="c1">Name</th>
            <th id="address" class="c2">Address</th>
            <th id="phone" class="c3">Phone</th>
        </tr>
    </thead> 
    <tbody>
        <tr>
            <td class="c1">Freddy</td>
            <td class="c2">Nightmare Street</td>
            <td class="c3">123</td>
        </tr>
        <tr>
            <td class="c1">Luis</td>
            <td class="c2">Lost Street</td>
            <td class="c3">3456</td>
        </tr>
    </tbody>
</table>
</body>
</html>

To hide a column, you add with Javascript the corresponding class to the table. 要隐藏列,可以使用Javascript将相应的类添加到表中。 Here c2 and c3 are hidden. 这里隐藏了c2和c3。

You could add dynamically the .c1, .c2,... in a style tag, or define a maximum number. 您可以在样式标记中动态添加.c1,.c2,...,或定义最大数字。

jQuery('thead td').click( function () {

    var th_index = jQuery(this).index();

    jQuery('#my_table tbody tr').each(
        function(index) {
            jQuery(this).children('td:eq(' + th_index + ');').each(
                function(index) {
                    // do stuff here
                }
            );
        }
    );
});

here's a working fiddle of this behaviour: 这是这种行为的工作小提琴:

http://jsfiddle.net/tycRW/ http://jsfiddle.net/tycRW/

of course, hiding the column with out hiding the header for it will have some strange results. 当然,隐藏列而不隐藏其标题会产生一些奇怪的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM