2012-09-26 109 views
2

已经提出了类似的问题,但我不确定它们是否匹配这个特定的场景,我有一个html表格,如下所示。 我想实现的是隐藏/显示列2和3,只要在列1中的任何地方有一个点击。用jQuery隐藏html表的中间列

我该如何实现切换显示第2列和第3列与jQuery?

<table id="my_table"> 
    <thead> 
     <tr> 
      <th id="col1">First</th> 
      <th id="col2">Second</th> 
      <th id="col3">Third</th> 
      <th id="col4">Fourth</th> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td id="col1">1</td> 
      <td id="col2">1.1</td> 
      <td id="col3">1.2</td> 
      <td id="col4">1.3</td> 
     </tr> 
     <tr> 
      <td id="col1">2</td> 
      <td id="col2">2.1</td> 
      <td id="col3">2.2</td> 
      <td id="col4">2.3</td> 
     </tr> 
     <tr> 
      <td id="col1">3</td> 
      <td id="col2">3.1</td> 
      <td id="col3">3.2</td> 
      <td id="col4">3.3</td> 
     </tr> 
     <tr> 
      <td id="col1">4</td> 
      <td id="col2">4.1</td> 
      <td id="col3">4.2</td> 
      <td id="col3">4.3</td> 
     </tr> 
    </tbody> 
    <tfoot> 
     <tr> 
      <th id="col1">f1</th> 
      <th id="col2">f2</th> 
      <th id="col3">f3</th> 
      <th id="col4">f4</th> 
     </tr> 
    </tfoot> 
</table> 

回答

3
var rows = $('tr'); 
rows.find('th:first-child, td:first-child').on('click', function() { 
    rows.find('td:eq(1), td:eq(2)').toggle() 
    rows.find('th:eq(1), th:eq(2)').toggle() 

    /* or simply 
     rows.find('td:eq(1), td:eq(2), th:eq(1), th:eq(2)').toggle(); */ 
}); 

例如jsbin:http://jsbin.com/ucewoz/2/edit

+0

不错,简单和伟大的作品。 – emt14

1

不能各行中使用相同的ID。 ID必须是唯一的。你应该使用类来代替。然后你可以写:

$('.col1').click(function() { 
    $('.col2, .col3').toggle(); 
}); 
+0

确实,好点... – emt14