本教程详细介绍了如何在 google apps script 项目中,为 html 表格实现多列动态搜索过滤功能。通过优化 javascript 代码,我们不再局限于单列搜索,而是能够遍历表格的每一行和每个单元格,从而实现对所有列内容的全面匹配,提升用户数据查找的灵活性和效率。
在 Google Apps Script 项目中,经常需要将 Google Sheets 中的数据展示在自定义的 HTML 界面上。为了提升用户体验,为这些 HTML 表格添加搜索过滤功能是必不可少的。然而,常见的单列搜索实现方式往往无法满足用户对数据进行多维度查找的需求。本教程将指导您如何修改现有的 JavaScript 代码,实现一个功能更强大的、能够对表格所有列内容进行搜索的动态过滤功能。
原始的过滤逻辑通常只针对表格的某一特定列(例如 tableRows[i].cells[1]),这限制了搜索的范围。要实现多列搜索,我们需要扩展这个逻辑,使其能够检查一行中的所有单元格。
解决方案的核心思路是:
以下是经过优化后的 JavaScript 代码,实现了对 HTML 表格所有列的动态搜索过滤:
/**
* 处理输入框内容变化事件,实现表格多列搜索过滤。
* 当用户在搜索框中输入文本时,此函数会被调用,
* 遍历表格中的每一行,并在行的所有单元格中查找匹配的文本,
* 从而决定显示或隐藏该行。
*/
function onInputChange() {
// 获取用户输入的搜索文本,并转换为小写以便进行不区分大小写的匹配
let inputText = document.getElementById("input-search").value.toString().toLowerCase();
// 获取表格的主体元素和所有行
let tableBody = document.getElementById("cursos");
let tableRows = tableBody.getElementsByTagName("tr");
// 遍历表格中的每一行
for (let i = 0; i < tableRows.length; i++) {
// 获取当前行的所有单元格(td 元素)
let rowCells = tableRows[i].getElementsByTagName("td");
let foundMatch = false; // 标志位,用于记录当前行是否找到匹配项
// 遍历当前行的所有单元格
for (let j = 0; j < rowCells.length; j++) {
// 获取单元格的文本内容,并转换为小写
let cellText = rowCells[j].textContent.toString().toLowerCase();
// 检查搜索文本是否包含在当前单元格的文本中
if (cellText.indexOf(inputText) !== -1) {
foundMatch = true; // 找到匹配项
break; // 在当前行找到匹配后,无需再检查该行的其他单元格,提高效率
}
}
// 根据是否找到匹配项来决定行的可见性
if (foundMatch) {
tableRows[i].style.visibility = ""; // 显示该行
} else {
tableRows[i].style.visibility = "collapse"; // 隐藏该行
}
}
}let inputText = document.getElementById("input-search").value.toString().toLowerCase
();let tableBody = document.getElementById("cursos");
let tableRows = tableBody.getElementsByTagName("tr"); 单元格。let cellText = rowCells[j].textContent.toString().toLowerCase();
if (cellText.indexOf(inputText) !== -1) {
foundMatch = true;
break;
}
if (foundMatch) {
tableRows[i].style.visibility = "";
} else {
tableRows[i].style.visibility = "collapse";
}
注意事项与最佳实践
|