我正在尝试使用复选框为表格创建切换过滤器。它工作正常,但我想知道是否有更有效和更清洁的方法。
https://jsfiddle.net/xh4Lc3j4/1/
谢谢,
$(document).ready(function() {
$(".sr-filter").find('ul').children('li:nth-child(1)').find('input').click(function() {
$(".sr-table").find('tr').children('*:nth-child(1)').fadeToggle();
});
$(".sr-filter").find('ul').children('li:nth-child(2)').find('input').click(function() {
$(".sr-table").find('tr').children('*:nth-child(2)').fadeToggle();
});
$(".sr-filter").find('ul').children('li:nth-child(3)').find('input').click(function() {
$(".sr-table").find('tr').children('*:nth-child(3)').fadeToggle();
});
$(".sr-filter").find('ul').children('li:nth-child(4)').find('input').click(function() {
$(".sr-table").find('tr').children('*:nth-child(4)').fadeToggle();
});
$(".sr-filter").find('ul').children('li:nth-child(5)').find('input').click(function() {
$(".sr-table").find('tr').children('*:nth-child(5)').fadeToggle();
});
});

答案 0 :(得分:4)
这可能有用,并且是纯粹的jQuery解决方案。
$(".sr-filter ul > li input").on("click", function() {
var nIndex = $(this).parent().index() + 1;
$(".sr-table tr *:nth-child("+nIndex+")").fadeToggle();
})
此示例有效,仅使用复选框字段。
$(".sr-filter ul > li input[type=checkbox]").on("change", function() {
var nIndex = $(this).parent().index() + 1;
$(".sr-table tr *:nth-child(" + nIndex + ")").fadeToggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table class="sr-table">
<tr>
<th>Sample 1</th>
<th>Sample 2</th>
<th>Sample 3</th>
<th>Sample 4</th>
<th>Sample 5</th>
</tr>
<tr>
<td>Sample 1a</td>
<td>Sample 2a</td>
<td>Sample 3a</td>
<td>Sample 4a</td>
<td>Sample 5a</td>
</tr>
<tr>
<td>Sample 1b</td>
<td>Sample 2b</td>
<td>Sample 3b</td>
<td>Sample 4b</td>
<td>Sample 5b</td>
</tr>
<tr>
<td>Sample 1c</td>
<td>Sample 2c</td>
<td>Sample 3c</td>
<td>Sample 4c</td>
<td>Sample 5c</td>
</tr>
</table>
<div class="sr-filter">
<ul>
<li>
<input type="checkbox" name="sr-filter-option" id="sr-filter-spa" checked/>
<label for="sr-filter-spa">Sample 1</label>
</li>
<li>
<input type="checkbox" name="sr-filter-option" id="sr-filter-spb" checked/>
<label for="sr-filter-spb">Sample 2</label>
</li>
<li>
<input type="checkbox" name="sr-filter-option" id="sr-filter-spc" checked/>
<label for="sr-filter-spc">Sample 3</label>
</li>
<li>
<input type="checkbox" name="sr-filter-option" id="sr-filter-spd" checked/>
<label for="sr-filter-spd">Sample 4</label>
</li>
<li>
<input type="checkbox" name="sr-filter-option" id="sr-filter-spe" checked/>
<label for="sr-filter-spe">Sample 5</label>
</li>
</ul>
</div>
</body>