2013-04-22 77 views
1



所有的Firtst,我是新手在使用Javascript/jQuery的,我發現計算器幾個例子對HTML表格中隱藏列,這正是我需要的:
hide table columns automatically by checking a checkbox with jQuery
它的工作原理上的jsfiddle:
http://jsfiddle.net/highwayoflife/8BahZ/4/

但我不知道,我是不是做錯了什麼,爲什麼它不工作對我來說,當我不得不把它放在一起: 由jquery隱藏列?

<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>tablazat</title> 
    <style> 
     td, th { 
      padding: 6px; 
      border: 1px solid black; 
     } 
     th { 
      background-color: #f0eae2; 
      font-weight: bold; 
     } 
     table { 
      border: 1px solid black; 
     } 
    </style> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> 
    <script language="javascript"> 
     $("input:checkbox:not(:checked)").each(function() { 
      var column = "table ." + $(this).attr("name"); 
      $(column).hide(); 
     }); 

     $("input:checkbox").click(function() { 
      var column = "table ." + $(this).attr("name"); 
      $(column).toggle(); 
     }); 
    </script> 
</head> 
<body> 

    <p><input type="checkbox" name="first_name" checked="checked" /> First Name</p> 
    <p><input type="checkbox" name="last_name" /> Last Name</p> 
    <p><input type="checkbox" name="email" checked="checked" /> Email</p> 

    <table id="report"> 
     <thead> 
      <tr> 
       <th class="first_name">First Name</th> 
       <th class="last_name">Last Name</th> 
       <th class="email">Email</th> 
      </tr> 
     </thead> 
     <tbody> 
      <tr> 
       <td class="first_name">Larry</td> 
       <td class="last_name">Hughes</td> 
       <td class="email">[email protected]</td> 
      </tr> 
      <tr> 
       <td class="first_name">Mike</td> 
       <td class="last_name">Tyson</td> 
       <td class="email">[email protected]</td> 
      </tr> 
     </tbody>  
    </table> 
</body> 

任何幫助表示讚賞:請儘量把它解釋爲簡單,因爲它是possib樂,就像我寫的。提前致謝!

+1

爲什麼你使用這樣一箇舊版本的jQuery? – Blazemonger 2013-04-22 14:36:06

+0

這個版本是張貼在例子上,我也試過它與1.9.1,但它仍然不工作:( – 2013-04-22 14:40:40

回答

2

你需要用你的代碼在$(document).ready塊,否則將它移動到頁面的底部,因爲這些複選框還不存在:

<script language="javascript"> 
    $(document).ready(function() { 
    $("input:checkbox:not(:checked)").each(function() { 
     var column = "table ." + $(this).attr("name"); 
     $(column).hide(); 
    }); 

    $("input:checkbox").click(function() { 
     var column = "table ." + $(this).attr("name"); 
     $(column).toggle(); 
    }); 
    }); 
</script> 
中的jsfiddle

,第二個下拉的左上角通常設置爲「onLoad」,這會自動觸發此行爲。

+0

非常感謝!它的工作原理!!! :) – 2013-04-22 14:45:03