Jquery 循环遍历 showing/hiding n 列 table 的 checbboxes 的函数

Jquery function for looping through checbboxes for showing/hiding n columns table

如何遍历我的所有复选框并检索输入 "checked or unchecked" 并传递给我的函数并隐藏或显示我的列 table?

我的HTML

<div class="columnchecking">
       <h1>Check/Uncheck for showing/hiding columns of table</h1>
       <br /> 
       <font size="4"><input id="formnamecheck" type="checkbox">Formname &emsp;</font>
       <font size="4"><input id="typecheck" type="checkbox">Type &emsp;</font> 
       <font size="4"><input id="languagecheck" type="checkbox">Language &emsp;</font> 
       <font size="4"><input id="gpartcheck" type="checkbox">Gpart &emsp;</font>
    </div>
    <table>
       <thead>
          <tr>
             <th>Formname</th>
             <th>Formname</th>
             <th>Type</th>
             <th>Language</th>
             <th>Gpart</th>
          </tr>
       </thead>
       <tbody>
          <tr>
             <td>Test</td>
             <td>Test</td>
             <td>Test</td>
             <td>Test</td>
          </tr>
       </tbody>
    </table>

Javascript:

<script type="text/javascript">
$(document).ready(function() {
    $("#formnamecheck").click(function() {
        if ($(this).is(':checked')) {
            $('td:nth-child(n),th:nth-child(n)').hide();
        } else {
            $('td:nth-child(n),th:nth-child(n)').show();
        }
    });
});

其中 N 是我 table

中的第 n 列

您必须先获取 N 的值!

$(document).ready(function() {
    $("#formnamecheck").click(function() {
        var n = $('input').index($(this))+1;
        if ($(this).is(':checked')) {
            $('td:nth-child('+n+'),th:nth-child('+n+')').hide();
        } else {
            $('td:nth-child('+n+'),th:nth-child('+n+')').show();
        }
    });
});

您可以将容器 div 元素添加到复选框以获取其中每个元素的索引,并在您想要使用 toggle() 作为较短的隐藏或显示特定列时使用它方法比 if ... else:

$(document).ready(function() {
  $("input[type='checkbox']").change(function() {
    var index = $(this).parent().index() + 1;
    $('td:nth-child(' + index + '),th:nth-child(' + index + ')').toggle($(this).is(':checked'));
  }).change();
});
td,
th {
  border: 2px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="columnchecking">
  <h1>Check/Uncheck for showing/hiding columns of table</h1>
  <br />
  <div class='checboxes_container'>
    <font size="4"><input id="formnamecheck" type="checkbox">Formname &emsp;</font>
    <font size="4"><input id="typecheck" type="checkbox">Type &emsp;</font>
    <font size="4"><input id="languagecheck" type="checkbox">Language &emsp;</font>
    <font size="4"><input id="gpartcheck" type="checkbox">Gpart &emsp;</font>
  </div>
</div>
<table>
  <thead>
    <tr>
      <th>Formname
      </th>
      <th>Type
      </th>
      <th>Language
      </th>
      <th>Gpart
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Test 1</td>
      <td>Test 2</td>
      <td>Test 3</td>
      <td>Test 4</td>
    </tr>
  </tbody>
</table>