簡體   English   中英

使用JavaScript隱藏表格列

[英]Hide a table column with Javascript

我有下表:

<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>

我要做的是隱藏最后一列,但是我無法更改表格的當前狀態。 我可以使用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';
        }
    }
}

不碰桌子怎么辦?

此代碼選擇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';
});

您不需要為此使用javascript。 您可以使用CSS選擇器隱藏最后一列:

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

編輯:剛意識到您特別需要在javascript中執行此操作。 不知道是否有任何方法可以在不觸摸表格的情況下附加樣式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM