带有复选框的排序表:内容不再可见

Sorting Table with checkbox: content is not visible anymore

本文关键字:不再 复选框 排序      更新时间:2023-09-26

这是表的HTML和我正在尝试的JS代码。基本上,单击复选框将出现另一个表:

<form class="filter">
<input type="checkbox" id="checkboxID" class="unchecked"> EG
<input type="checkbox" id="checkbox1OG" class="unchecked"> 1.OG
<input type="checkbox" id="checkbox2OG" class="unchecked"> 2.OG
<input type="checkbox" id="checkbox3OG" class="unchecked"> 3.OG
</form>
<script>
 $('input.unchecked').on('change', function() {
 $('input.unchecked').not(this).prop('checked', false);  
});
</script>

<script>
$("#checkboxID").change(function(){
$("#tableID tr.rowEG").toggle(!this.checked); 
});
    $("#checkbox1OG").change(function(){
$("#tableID tr.row1OG").toggle(!this.checked); 
});
    $("#checkbox2OG").change(function(){
$("#tableID tr.row2OG").toggle(!this.checked); 
});
    $("#checkbox3OG").change(function(){
$("#tableID tr.row3OG").toggle(!this.checked); 
});
</script>

但是在单击时,表格消失了。

如果您选中了一个复选框,然后选择另一个复选框而不手动取消选择前一个复选框,则会出现此问题。否则效果很好。

我建议你定义一个这样的函数:

function restore_table() {
    $("#tableID tr.rowEG").toggle(true);
    $("#tableID tr.row1OG").toggle(true);
    $("#tableID tr.row2OG").toggle(true);
    $("#tableID tr.row3OG").toggle(true);
}

然后,您可以在操作表行之前对每个单独的change()调用调用此函数。例如:

// Do this with the four change calls
$("#checkboxEG").change(function(){
    restore_table();
    $("#tableID tr.rowEG").toggle(!this.checked); 
});

每个复选框都会过滤具有特定类的行,这意味着当您选中第一个chckbox然后单击另一个时,第二个复选框找不到具有它正在搜索的类的行,我的意思是,当您选中一个复选框然后选中另一个复选框时,.on(change)方法,仅管理复选框检查,而不删除过滤...

$('input.unchecked').on('change', function() {
 $('input.unchecked').not(this).prop('checked', false);  
});

您应该在执行任何新的过滤之前重置过滤的行...

function restRows(){
$('#tableID tr').filter(function() {
   return $(this).css('display') == 'none';
}).show();
}

并在像这样进行任何过滤之前调用它:

    $("#checkbox3OG").change(function(){
    //reset all hidden rows
    restRows();
    //filter new rows
    $("#tableID tr.row3OG").hide();
});