如何用jQuery/JS筛选表格中无班级学生并隐藏其余行
实现方案
你可以选择jQuery或原生JS两种实现方式,代码可直接复用:
jQuery实现
直接绑定按钮点击事件即可:
$('#add-student').on('click', function() { $('.clickable_student').each(function() { const classVal = $(this).find('.Class-name').text().trim(); $(this).toggle(classVal === ''); }); });
如果需要按钮支持「显示无班级学生/显示全部学生」切换,可使用以下代码:
$('#add-student').on('click', function() { const showEmpty = $(this).data('showEmpty') || false; if (showEmpty) { $('.clickable_student').show(); $(this).text('Show Student with no Class'); } else { $('.clickable_student').each(function() { const classVal = $(this).find('.Class-name').text().trim(); $(this).toggle(classVal === ''); }); $(this).text('Show All Students'); } $(this).data('showEmpty', !showEmpty); });
原生JavaScript实现(无需引入jQuery)
基础版本:
document.querySelector('#add-student').addEventListener('click', () => { document.querySelectorAll('.clickable_student').forEach(row => { const classVal = row.querySelector('.Class-name').textContent.trim(); row.style.display = classVal === '' ? 'table-row' : 'none'; }); });
切换版本:
document.querySelector('#add-student').addEventListener('click', function() { const showEmpty = this.dataset.showEmpty === 'true'; const rows = document.querySelectorAll('.clickable_student'); if (showEmpty) { rows.forEach(row => row.style.display = 'table-row'); this.textContent = 'Show Student with no Class'; } else { rows.forEach(row => { const classVal = row.querySelector('.Class-name').textContent.trim(); row.style.display = classVal === '' ? 'table-row' : 'none'; }); this.textContent = 'Show All Students'; } this.dataset.showEmpty = !showEmpty; });
注意
代码中使用trim()处理文本是为了适配你当前HTML结构里,空班级列td中存在换行、空格的场景,保证判断准确。
内容的提问来源于stack exchange,提问作者rixemo2349
相关产品推荐
相关产品推荐

