2015-09-04 132 views
2

我有如下表:隱藏表列使用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'; 
     } 
    } 
} 

我能做些什麼,而不觸及表?

+0

您可以使用CSS選擇器來選擇最後TD喜歡使用 「TD:最後的孩子」 –

+0

你可以用布爾值替換一些表達式。例如4> = 0,您可以用true替換。 4是每次更多(或相等)比0. – Misaz

回答

1

此選擇THES的cols細胞(TH和TD),然後隱藏它們(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'; 
}); 
+0

哇,這裏的工作真的很好 –

+0

感謝您的幫助和耐心,我是新來的:) –

1

您無需爲此使用JavaScript。您可以使用CSS選擇器來隱藏最後一欄

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

編輯:剛剛意識到你特別需要做的是在JavaScript。不知道是否有任何方法可以在不觸摸桌子的情況下追加樣式。

+0

是的,只有Javascript,但thans您的支持:) –

+0

您的回答對我非常有幫助。很高興你發佈它。 –