2013-04-22 62 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