
本教程将指导您如何利用javascript实现一个动态数据表格的搜索功能。通过从api获取数据并将其存储在全局变量中,我们能够结合用户输入,使用数组的`filter()`方法高效地筛选出匹配项,并实时更新html表格,从而为用户提供一个响应式且高效的数据查询体验。
在现代Web应用中,动态展示和搜索大量数据是常见的需求。本教程将详细介绍如何使用纯JavaScript,结合API数据和HTML表格,实现一个高效且用户友好的搜索功能。
为了实现高效的搜索功能,避免每次用户搜索时都重新请求API,我们应该在页面加载时一次性获取所有数据,并将其存储在一个全局可访问的变量中。
首先,定义一个全局变量 countriesData 用于存储从API获取的原始国家数据。
let countriesData = []; // 全局变量,用于存储所有国家数据
/**
* 异步获取API数据
*/
const getdata = async () => {
const endpoint = "https://api.covid19api.com/summary";
try {
const response = await fetch(endpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
countriesData = data.Countries; // 将获取到的国家数据存储到全局变量
_DisplayCountries(); // 数据加载完成后,立即显示所有国家
} catch (error) {
console.error("获取数据失败:", error);
// 可以添加用户友好的错误提示
}
}
getdata(); // 页面加载时调用,获取并显示数据我们需要一个输入框供用户输入搜索关键词,一个按钮触发搜索,以及一个HTML表格来展示数据。
立即学习“Java免费学习笔记(深入)”;
<!-- 搜索框与搜索按钮 -->
<input type="text" id="myInput" placeholder=" 搜索国家 ">
<input type="submit" id="mySubmit" value="搜索" class="submit">
<!-- 数据表格 -->
<table class="table">
<thead>
<tr>
<th scope="col">国家</th>
<th scope="col">新增确诊</th>
<th scope="col">累计确诊</th>
<th scope="col">新增死亡</th>
<th scope="col">累计死亡</th>
<th scope="col">新增治愈</th>
<th scope="col">累计治愈</th>
<th scope="col">最后更新时间</th>
</tr>
</thead>
<tbody id="tbody">
<!-- 数据将动态加载到这里 -->
</tbody>
</table>注意: 确保搜索按钮有一个唯一的 id (例如 mySubmit),以便我们可以在JavaScript中轻松地为其添加事件监听器。
这是实现搜索功能的核心部分。我们将创建一个独立的函数 _DisplayCountries,它负责根据传入的搜索关键词过滤 countriesData,并更新HTML表格。
/**
* 根据关键词过滤并显示国家数据
* @param {string} searchTerm - 用户输入的搜索关键词,默认为空字符串
*/
const _DisplayCountries = (searchTerm = "") => {
const tbody = document.querySelector("#tbody");
tbody.innerHTML = ``; // 清空表格当前内容
// 使用filter方法过滤数据
const filteredCountries = countriesData.filter(country =>
// 将国家名称和搜索关键词都转换为小写,实现大小写不敏感搜索
country.Country.toLowerCase().includes(searchTerm.toLowerCase())
);
// 遍历过滤后的数据,并将其添加到表格中
filteredCountries.forEach(result => {
tbody.innerHTML += `<tr>
<td>${result.Country}</td>
<td>${result.NewConfirmed}</td>
<td>${result.TotalConfirmed}</td>
<td>${result.NewDeaths}</td>
<td>${result.TotalDeaths}</td>
<td>${result.NewRecovered}</td>
<td>${result.TotalRecovered}</td>
<td>${new Date(result.Date).toLocaleString()}</td>
</tr>`;
});
// 如果没有搜索结果,可以显示提示信息
if (filteredCountries.length === 0 && searchTerm !== "") {
tbody.innerHTML = `<tr><td colspan="8" style="text-align: center;">未找到匹配 "${searchTerm}" 的国家。</td></tr>`;
}
}在这个函数中,我们首先清空 <tbody> 的内容,然后使用 Array.prototype.filter() 方法根据 searchTerm 过滤 countriesData 数组。为了实现大小写不敏感的搜索,我们将 country.Country 和 searchTerm 都转换为小写再进行比较。最后,遍历过滤后的结果,并构建相应的表格行。
最后一步是监听搜索按钮的点击事件。当用户点击“搜索”按钮时,我们获取输入框中的值,并将其传递给 _DisplayCountries 函数。
document.querySelector("#mySubmit").addEventListener("click", () => {
const searchInput = document.querySelector("#myInput");
_DisplayCountries(searchInput.value); // 调用显示函数,传入搜索框的值
});将以上所有JavaScript和HTML代码组合起来,即可实现完整的搜索功能。
HTML (index.html):
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>可搜索的动态数据表格</title>
<style>
body { font-family: sans-serif; margin: 20px; }
.table { width: 100%; border-collapse: collapse; margin-top: 20px; }
.table th, .table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
.table th { background-color: #f2f2f2; }
#myInput { padding: 8px; width: 200px; margin-right: 10px; border: 1px solid #ccc; border-radius: 4px;}
#mySubmit { padding: 8px 15px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
#mySubmit:hover { background-color: #0056b3; }
</style>
</head>
<body>
<h1>全球疫情数据查询</h1>
<!-- 搜索框与搜索按钮 -->
<input type="text" id="myInput" placeholder=" 搜索国家 ">
<input type="submit" id="mySubmit" value="搜索" class="submit">
<!-- 数据表格 -->
<table class="table">
<thead>
<tr>
<th scope="col">国家</th>
<th scope="col">新增确诊</th>
<th scope="col">累计确诊</th>
<th scope="col">新增死亡</th>
<th scope="col">累计死亡</th>
<th scope="col">新增治愈</th>
<th scope="col">累计治愈</th>
<th scope="col">最后更新时间</th>
</tr>
</thead>
<tbody id="tbody">
<!-- 数据将动态加载到这里 -->
</tbody>
</table>
<script src="app.js"></script>
</body>
</html>let countriesData = []; // 全局变量,用于存储所有国家数据
/**
* 异步获取API数据
*/
const getdata = async () => {
const endpoint = "https://api.covid19api.com/summary";
try {
const response = await fetch(endpoint);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
countriesData = data.Countries; // 将获取到的国家数据存储到全局变量
_DisplayCountries(); // 数据加载完成后,立即显示所有国家
} catch (error) {
console.error("获取数据失败:", error);
const tbody = document.querySelector("#tbody");
tbody.innerHTML = `<tr><td colspan="8" style="text-align: center; color: red;">数据加载失败,请稍后再试。</td></tr>`;
}
}
/**
* 根据关键词过滤并显示国家数据
* @param {string} searchTerm - 用户输入的搜索关键词,默认为空字符串
*/
const _DisplayCountries = (searchTerm = "") => {
const tbody = document.querySelector("#tbody");
tbody.innerHTML = ``; // 清空表格当前内容
// 使用filter方法过滤数据
const filteredCountries = countriesData.filter(country =>
// 将国家名称和搜索关键词都转换为小写,实现大小写不敏感搜索
country.Country.toLowerCase().includes(searchTerm.toLowerCase())
);
// 遍历过滤后的数据,并将其添加到表格中
if (filteredCountries.length > 0) {
filteredCountries.forEach(result => {
tbody.innerHTML += `<tr>
<td>${result.Country}</td>
<td>${result.NewConfirmed}</td>
<td>${result.TotalConfirmed}</td>
<td>${result.NewDeaths}</td>
<td>${result.TotalDeaths}</td>
<td>${result.NewRecovered}</td>
<td>${result.TotalRecovered}</td>
<td>${new Date(result.Date).toLocaleString()}</td>
</tr>`;
});
} else {
// 如果没有搜索结果,可以显示提示信息
tbody.innerHTML = `<tr><td colspan="8" style="text-align: center;">未找到匹配 "${searchTerm}" 的国家。</td></tr>`;
}
}
// 页面加载时调用,获取并显示数据
getdata();
// 绑定搜索按钮点击事件
document.querySelector("#mySubmit").addEventListener("click", () => {
const searchInput = document.querySelector("#myInput");
_DisplayCountries(searchInput.value); // 调用显示函数,传入搜索框的值
});为了提升用户体验和代码的灵活性,我们可以考虑以下优化和扩展:
大小写不敏感匹配的替代方案: 除了 toLowerCase().includes(),还可以使用正则表达式进行更灵活的匹配。例如:
const _DisplayCountries = (searchTerm = "") => {
const tbody = document.querySelector("#tbody");
tbody.innerHTML = ``;
// 创建一个正则表达式,'i' 标志表示不区分大小写
const regex = new RegExp(searchTerm, "i");
const filteredCountries = countriesData.filter(country =>
country.Country.match(regex)
);
// ... 后续渲染逻辑不变
}这种方式在处理更复杂的模式匹配时更为强大。
实时搜索(即时过滤): 将事件监听器从搜索按钮的 click 事件改为搜索输入框的 input 或 keyup 事件,可以在用户输入时立即更新结果,提供更流畅的体验。
document.querySelector("#myInput").addEventListener("input", (e) => {
_DisplayCountries(e.target.value);
});
// 如果改为实时搜索,搜索按钮可以移除或改变其功能
// document.querySelector("#mySubmit").removeEventListener("click", ...);性能考量(防抖/节流): 对于实时搜索,如果数据集非常庞大,频繁触发过滤和DOM操作可能会导致性能问题。此时可以引入防抖(debounce)或节流(throttle)技术,限制函数的执行频率。
用户体验增强:
错误处理: 在 getdata 函数中添加 try...catch 块,可以捕获API请求或解析数据时可能发生的错误,并向用户提供反馈,增强应用的健壮性。
通过本教程,我们学习了如何利用JavaScript实现一个动态数据表格的搜索功能。核心步骤包括:一次性获取并全局存储API数据、构建清晰的HTML结构、使用 Array.prototype.filter() 方法结合大小写不敏感匹配逻辑进行数据过滤,以及将过滤后的数据动态渲染到HTML表格中。通过分离数据获取、过滤和显示逻辑,并考虑事件绑定和性能优化,我们可以构建出高效、响应式且用户体验良好的Web应用。
以上就是构建可搜索的动态表格:JavaScript与API数据过滤教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号