简体   繁体   English

使用JavaScript隐藏表格列

[英]Hide a table column with Javascript

I have the following table: 我有下表:

<table id="btt-ranges" cellspacing="0" cellpadding="0" border="0" 
    <tbody>
        <tr>
            <th scope="col"> </th>
            <th id="Business" scope="col">Type of Business</th>
            <th id="Ranges" scope="col"> Ranges</th>
            <th scope="col">BTT</th>
        </tr>
        <tr>
            <td>Example</td>
            <td>Example</td>
            <td>Example</td>
            <td>Example</td>
        </tr>
        <tr>
            <td>Example</td>
            <td>Example</td>
            <td>Example</td>
            <td>Example</td>
        </tr>
        <tr>
            <td>Example</td>
            <td>Example</td>
            <td>Example</td>
            <td>Example</td>
        </tr>
    </tbody>
</table>

What I have to do is hide the last column, but I can't change how the table is right now. 我要做的是隐藏最后一列,但是我无法更改表格的当前状态。 I can use Javascript and so far this is what I tried: 我可以使用Javascript,到目前为止,这是我尝试过的操作:

function show_hide_column() {
    var tbl = document.getElementById('btt-changes');
    var rows = tbl.getElementsByTagName('tr');

    for (var row = 0; row < rows.length; row++) {
        var cols = rows[row].children;
        console.log(1, cols.length);
        if (4 >= 0 && 4 < cols.length) {
            var cell = cols[4];
            console.log(cell, cell.tagName);
            if (cell.tagName == 'TD') cell.style.display = 'none';
        }
    }
}

What can I do without touching the table? 不碰桌子怎么办?

This code selects the col's cells (th and tds), and then hides them ( fiddle ): 此代码选择col的单元格(th和tds),然后将其隐藏( fiddle ):

var lastColHeader = Array.prototype.slice.call(document.querySelectorAll('th:last-child', '#btt-ranges'), 0); // get the header cell
var lastColCells = Array.prototype.slice.call(document.querySelectorAll('td:last-child', '#btt-ranges'), 0).concat(lastColHeader); // get the column cells, and add header

lastColCells.forEach(function(cell) { // iterate and hide
    cell.style.display = 'none';
});

You don't need to use javascript for this. 您不需要为此使用javascript。 You can use a CSS selector to hide the last column: 您可以使用CSS选择器隐藏最后一列:

#btt-ranges tr td:last-child { display: none; }

Edit: Just realized you specifically need to do it in javascript. 编辑:刚意识到您特别需要在javascript中执行此操作。 Not sure if there is any way to append a style without touching the table. 不知道是否有任何方法可以在不触摸表格的情况下附加样式。

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

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