隐藏表JavaScript中的列

问题描述:

当我在表格中添加表格时,此脚本会停止工作,那么如何使其工作?
我不需要任何jQuery解决方案,我想要纯JavaScript。这是我在互联网上找到的脚本

This script stops working the moment I add a table inside a table, so how to get it worked? I don't need any jQuery solutions, I want pure JavaScript. Here's my script found on the Internet:

<script>

  function show_hide_column(col_no, do_show) {

    var stl;
    if (do_show) stl = 'block'
    else         stl = 'none';

    var tbl  = document.getElementById('id_of_table');
    var rows = tbl.getElementsByTagName('tr');

    for (var row=1; row<rows.length;row++) {
      var cels = rows[row].getElementsByTagName('td')
      cels[col_no].style.display=stl;
    }
  }

</script>

这是我的 HTML

<table id='id_of_table' border=1>
  <tr><td colspan="4"><table><tr><td></td></tr></table></td></tr>
  <tr><td>  2</td><td>   two</td><td>   deux</td><td>     zwei</td></tr>
  <tr><td>  3</td><td> three</td><td>  trois</td><td>     drei</td></tr>
  <tr><td>  4</td><td>  four</td><td>quattre</td><td>     vier</td></tr>
  <tr><td>  5</td><td>  five</td><td>   cinq</td><td>f&uuml;nf</td></tr>
  <tr><td>  6</td><td>   six</td><td>    six</td><td>    sechs</td></tr>
</table>

这是我的表格

<form>
  Enter column no: <input type='text' name=col_no><br>
  <input type='button' onClick='javascript:show_hide_column(col_no.value,  true);' value='show'>
  <input type='button' onClick='javascript:show_hide_column(col_no.value, false);' value='hide'>
</form>


如果你可以利用 col 标记解决方案,在纯JavaScript中,很简单:

If you can leverage the col tag the solution, in pure javascript, is straightforward:

<table id='id_of_table' border=1>
  <col class="col1"/>
  <col class="col2"/>
  <col class="col3"/>
  <col class="col4"/>
  <tr><td colspan="4"><table><tr><td></td></tr></table></td></tr>
  <tr><td>  2</td><td>   two</td><td>   deux</td><td>     zwei</td></tr>
  <tr><td>  3</td><td> three</td><td>  trois</td><td>     drei</td></tr>
  <tr><td>  4</td><td>  four</td><td>quattre</td><td>     vier</td></tr>
  <tr><td>  5</td><td>  five</td><td>   cinq</td><td>f&uuml;nf</td></tr>
  <tr><td>  6</td><td>   six</td><td>    six</td><td>    sechs</td></tr>
</table>

您可以只应用col几个css属性,但可见性就是其中之一

You can apply to col just a couple of css attributes, but visibility is one of them

function show_hide_column(col_no, do_show) {
   var tbl = document.getElementById('id_of_table');
   var col = tbl.getElementsByTagName('col')[col_no];
   if (col) {
     col.style.visibility=do_show?"":"collapse";
   }
}

参考文献:

  • col
  • visibility on quirksmode