复选框隐藏表中的行组 [英] Checkboxes hide groups of rows from a table
问题描述
我有一个表,我想动态隐藏/显示行,根据顶部的复选框。
I have a table that I would like to dynamically hide/reveal rows in, based on checkboxes at the top.
我想这样做没有jquery,只是vanilla javascript。
I would like to do this without jquery, just vanilla javascript.
网站和其他,但总是代码段,不完整的工作示例。
I have seen numerous methods on this site and others, but always snippets of code,not complete working examples.
我不想给每一行一个单独的div名称,或者任何,我假设有一种方法,我可以做一个公共类为3
I don't want to give each row a separate div name, or whatever, I am assuming there is a way I can do this with a common class for the 3 types of rows I want to hide/reveal.
任何人都可以告诉我一个工作示例,它允许复选框使用vanilla javascript从表格中隐藏/显示多行数据。
Can anyone please show me a working example which allows checkboxes to hide/show multiple rows from a table with vanilla javascript?
谢谢!
推荐答案
/ p>
Given HTML like the following:
<table>
<thead>
<tr>
<td>
<label>
<input type="checkbox" class="show" value="north" checked />North</label>
</td>
</tr>
<tr>
<td>
<label>
<input type="checkbox" class="show" value="south" checked />South
</label>
</td>
</tr>
<tr>
<td>
<label>
<input type="checkbox" class="show" value="outOfArea" checked />Out of area
</label>
</td>
</tr>
</thead>
<tbody>
<tr class="north">
<td>North One</td>
</tr>
<tr class="north">
<td>North Two</td>
</tr>
<tr class="outOfArea">
<td>Out-of-area One</td>
</tr>
<tr class="south">
<td>South One</td>
</tr>
<tr class="south">
<td>South Two</td>
</tr>
<tr class="north">
<td>North Three</td>
</tr>
<tr class="north">
<td>North Four</td>
</tr>
<tr class="south">
<td>South Three</td>
</tr>
<tr class="outOfArea">
<td>Out-of-area Two</td>
</tr>
</tbody>
</table>
以下jQuery看起来像你 p>
The following jQuery seems to do as you seem to describe:
$('thead input[type=checkbox]').change(function(){
var self = this;
$(self).closest('table').find('tbody tr').filter('.' + self.value).toggle(self.checked);
});
由于似乎你更喜欢纯JavaScript方法,我建议你与上面发布的相同的HTML):
As it seems that you'd prefer a plain-JavaScript approach, I'd suggest the following (to work on the same HTML as posted above):
function toggle (e) {
var self = e.target,
toggleClass = '.' + self.value,
toToggle = document.querySelectorAll(toggleClass);
for (var i = 0, len = toToggle.length; i < len; i++) {
toToggle[i].style.display = self.checked ? 'table-row' : 'none';
}
}
var thead = document.querySelector('thead');
thead.addEventListener('change', toggle);
参考文献:
- jQuery:
- Attribute-equals(
[attribute =value]
)selector 。 -
change()
。 -
closest()
。 -
find()
。 -
filter()
-
toggle()
。
- jQuery:
- Attribute-equals (
[attribute="value"]
) selector. change()
.closest()
.find()
.filter()
.toggle()
.
document.querySelector()
.document.querySelectorAll()
.EventTarget.addEventListener()
.
这篇关于复选框隐藏表中的行组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Attribute-equals (
- Attribute-equals(