【问题标题】:JQuery - Hide Table ColumnsJQuery - 隐藏表格列
【发布时间】:2017-04-06 15:33:50
【问题描述】:

我目前正在学习 JQuery。我已将 JQuery 文件保存在我的 wwwroot 文件夹中。脚本和HTML如下:

<head>
<script src="jquery-3.2.0.js">
</head>
<script>
$("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>
<p><input type="checkbox" name="first_name" checked="checked"> First Name 
  <input type="checkbox" name="last_name"> Last Name 
  <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">larry@gmail.com</td>
</tr>
<tr>
 <td class="first_name">Mike</td>
 <td class="last_name">Tyson</td>
 <td class="email">mike@gmail.com</td>
</tr>
</tbody>

我正在尝试通过复选框添加和删除列,但它根本不起作用。 我不明白为什么它不起作用?有人有什么想法吗?

【问题讨论】:

  • @freedomn-m 它说'function jquery()'
  • @freedomn-m 还有其他建议吗?
  • 当您调用您的代码时,它会作用于当时存在的任何元素。由于您的代码是 before 元素,因此没有任何元素,因此什么也不做。你有两个选择,最好:包裹在$(document).ready(function() { ..code here.. });(已经被建议作为答案) - 第二:把你的代码放在最后,就在&lt;/html&gt;之前而不是顶部。虽然这是一个短期修复,但 document.ready 是可行的方法。
  • 在您的脚本块中,添加:alert($("input:checkbox").length) - 它将为零。现在把同样的警报放在最后,假设 jquery 正在工作,它将显示正确的计数。
  • 这显然是一道作业题,我今天看到的第二道题

标签: jquery


【解决方案1】:

我认为您正在尝试执行以下操作:

$(document).on('change', 'input:checkbox', function() {
    if($(this).is(':checked')){
        var column = "table ." + $(this).attr("name");
        $(column).toggle();
    }else{
      var column = "table ." + $(this).attr("name");
        $(column).hide();   
    }
});

检测复选框的修改。 参考:How to detect a checkbox click in jQuery

【讨论】:

    【解决方案2】:

    将您的代码包装在 document.ready 函数中

      $(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();
            });
       });
    

    【讨论】:

    • "调用 jquery 时需要初始化"
    • 除了问题中提供的代码之外,您的页面中还有其他代码吗?
    猜你喜欢
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    相关资源
    最近更新 更多