我如何遍历我的所有复选框并检索“已选中或未选中”的输入并将其传递给我的函数并隐藏或显示我的列表?
我的 HTML
<div class="columnchecking">
<h1>Check/Uncheck for showing/hiding columns of table</h1>
<br />
<font size="4"><input id="formnamecheck" type="checkbox">Formname  </font>
<font size="4"><input id="typecheck" type="checkbox">Type  </font>
<font size="4"><input id="languagecheck" type="checkbox">Language  </font>
<font size="4"><input id="gpartcheck" type="checkbox">Gpart  </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 是我表中的第 n 列
最佳答案
您可以将容器 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  </font>
<font size="4"><input id="typecheck" type="checkbox">Type  </font>
<font size="4"><input id="languagecheck" type="checkbox">Language  </font>
<font size="4"><input id="gpartcheck" type="checkbox">Gpart  </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>
关于javascript - 用于循环显示/隐藏复选框和列表的 Jquery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43230798/