单击复选框以切换表格元素的功能

问题描述 投票:1回答:2

我一直试图使用此JS隐藏一些html table thtd元素。

$(document).ready(function(){
    $('th.proces').hide();
    $('td.proces').hide();
    $('#hide_proces').click(function() {
        if($(this).attr('checked'))
        {
            $('th.proces').show();
            $('td.proces').show();
        }
        else
        {
            $('th.proces').hide();
            $('td.proces').hide();
        }
    });
});

当页面加载时,项目被隐藏,因此可以正常工作。

现在我有了此复选框,并且当选中thtd元素时,应再次使其可见。

<input id="hide_proces" type="checkbox"/>
<th class="proces">Proces</th>
<td class="proces">some content</td>

选中此复选框后,元素仍然不可见,控制台中也没有错误。有什么建议吗?

javascript html
2个回答
0
投票

使用this.checked检查复选框的值,然后使用显示或隐藏以显示列,

请参见以下代码段

$(document).ready(function(){
    $('th.proces').hide();
    $('td.proces').hide();
    
    
    $("#hide_proces").on("click",function(e){
      this.checked ? ($('th.proces').show(),$('td.proces').show())
                   : ($('th.proces').hide(),$('td.proces').hide());
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

show process :<input id="hide_proces" type="checkbox" />


<br /><br /><br />

<table>
  <tr>
    <th class="proces">proces</th>
    <th>Item</th>
    <th>Amount</th>
  </tr>
  <tr>
    <td class="proces">some text  1!</td>
    <td>Apples</td>
    <td>$15</td>
  </tr>
  <tr>
    <td class="proces">some text 2 !</td> 
    <td>Orange</td>
    <td>$9</td>
  </tr>
  <tr>
    <td class="proces">some text 3 !</td> 
    <td>Bananas</td>
    <td>$7</td>
  </tr>
</table>

0
投票

尝试一下

$(document).ready(function(){
    $('th.proces').hide();
    $('td.proces').hide();
    const $hideProcess = $('#hide_proces');
    $hideProcess.click(function() {
        if($hideProcess.is(':checked'))
        {
            $('th.proces').show();
            $('td.proces').show();
        }
        else
        {
            $('th.proces').hide();
            $('td.proces').hide();
        }
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.