2023-08-20 15:55:50
HTML表格搜索功能可通过前端JavaScript实现,核心是监听输入框事件并遍历表格行匹配关键词,支持模糊匹配、精确匹配、多列搜索及性能优化。 以下是详细实现方法:
一、基础模糊匹配实现核心逻辑:监听输入框变化,遍历表格行,检查行内容是否包含关键词(不区分大小写)。
<input type="text" id="searchInput" placeholder="输入关键词搜索"><table id="dataTable"> <thead><tr><th>姓名</th><th>年龄</th><th>职业</th></tr></thead> <tbody> <tr><td>张三</td><td>25</td><td>程序员</td></tr> <tr><td>李四</td><td>30</td><td>设计师</td></tr> </tbody></table><script> const searchInput = document.getElementById('searchInput'); const tableRows = document.querySelectorAll('#dataTable tbody tr'); searchInput.addEventListener('input', () => { const searchTerm = searchInput.value.toLowerCase(); tableRows.forEach(row => { const rowData = row.textContent.toLowerCase(); row.style.display = rowData.includes(searchTerm) ? '' : 'none'; }); });</script>关键点:
核心逻辑:使用正则表达式^keyword$确保单元格内容与关键词完全一致。
searchInput.addEventListener('input', () => { const searchTerm = searchInput.value.toLowerCase(); tableRows.forEach(row => { let isMatch = false; const cells = row.querySelectorAll('td'); cells.forEach(cell => { const cellText = cell.textContent.toLowerCase(); if (new RegExp(`^${searchTerm}$`).test(cellText)) { isMatch = true; } }); row.style.display = isMatch ? '' : 'none'; });});关键点:
核心逻辑:指定需搜索的列索引,仅在这些列中查找关键词。
const searchColumns = [0, 2]; // 搜索姓名(0)和职业(2)列searchInput.addEventListener('input', () => { const searchTerm = searchInput.value.toLowerCase(); tableRows.forEach(row => { let isMatch = false; searchColumns.forEach(colIndex => { const cell = row.querySelector(`td:nth-child(${colIndex + 1})`); if (cell && cell.textContent.toLowerCase().includes(searchTerm)) { isMatch = true; } }); row.style.display = isMatch ? '' : 'none'; });});关键点:
节流(Throttling)延迟执行搜索逻辑,减少频繁触发:
let timeoutId;searchInput.addEventListener('input', () => { clearTimeout(timeoutId); timeoutId = setTimeout(() => { // 搜索逻辑 }, 300); // 300毫秒后执行});分页(Pagination)仅显示当前页数据,减少搜索范围:
const rowsPerPage = 10;let currentPage = 1;function renderPage(page) { const start = (page - 1) * rowsPerPage; const end = start + rowsPerPage; tableRows.forEach((row, index) => { row.style.display = (index >= start && index < end) ? '' : 'none'; });}虚拟DOM(Virtual DOM)使用React/Vue等框架,仅更新变化部分,避免全表重渲染。
Web Workers将搜索逻辑移至后台线程:
// 主线程const worker = new Worker('searchWorker.js');searchInput.addEventListener('input', () => { worker.postMessage(searchInput.value);});// searchWorker.jsself.onmessage = (e) => { const searchTerm = e.data.toLowerCase(); // 执行搜索并返回结果};减少DOM操作批量操作DOM,例如使用DocumentFragment或隐藏整个tbody后重建。
总结: