我有一个在开始和结束列处包含 rowspan
的表格。布局是:
<input type="button" id="btn" value="Hide" />
<div id="result">
<table>
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
<th>Column3</th>
<th>Hide</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2">Col1</td>
<td>col2</td>
<td>col3</td>
<td rowspan="2"><input type="checkbox" value="" /></td>
</tr>
<tr>
<td>col2</td>
<td>col3</td>
</tr>
<tr>
<td>Col1</td>
<td>col2</td>
<td>col3</td>
<td><input type="checkbox" value="" /></td>
</tr>
</tbody>
</table>
</div>
jquery代码是:
$("#btn").on("click",function(){
$('#result > table').find('input:checkbox:checked').closest('tr').toggle();
});
预计会同时隐藏 row1 和 row2,因为两行 (rowspan) 只有一个复选框,但它没有发生。它只隐藏第 1 行。
如何解决?
最佳答案
您可以检查下一行是否有更少的行 - 如果是,则它是一个 rowspan,因此您可以将其隐藏:
$("#btn").on("click",function(){
var row = $('#result > table').find('input:checkbox:checked').closest('tr'),
rowspan = row.next();
row.toggle();
if (rowspan.children().length < row.children().length) {
rowspan.toggle();
}
});
编辑
根据评论 - 任何列中任意数量的行跨度的解决方案:
$("#btn").on("click",function(){
$('#result > table').find('input:checkbox:checked').closest('tr').each(function() {
var row = $(this),
columns = row.children('td[rowspan]'),
rowsToSpan = 0;
row.toggle();
if (columns.length) {
columns.each(function() {
var thisRowSpan = parseInt($(this).attr('rowspan'));
if (thisRowSpan > rowsToSpan) {
rowsToSpan = thisRowSpan;
}
});
var nextRow = row.next();
for (var i = 1; i < rowsToSpan; i++) {
nextRow.toggle();
nextRow = nextRow.next();
}
}
});
});
关于jquery - 如何用rowspan隐藏行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32497024/