
本教程详细讲解如何使用javascript实现前端数据搜索功能。通过从api获取数据并将其存储,我们演示了如何利用`array.prototype.filter()`方法根据用户输入动态筛选数据,并实时更新html表格内容。文章涵盖了数据获取、存储、渲染以及搜索逻辑的实现,并提供了完整的代码示例和优化建议,帮助开发者构建高效的用户界面。
在现代Web应用中,从API获取大量数据并提供用户友好的搜索功能是常见的需求。本教程将指导您如何使用纯JavaScript实现这一功能,包括数据获取、本地存储、动态渲染以及基于用户输入的搜索过滤。
实现前端数据搜索功能的核心在于以下几点:
首先,我们需要一个包含搜索框、搜索按钮和数据展示表格的基础HTML结构。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API数据搜索示例</title>
<style>
body { font-family: sans-serif; margin: 20px; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
input[type="text"], input[type="submit"] { padding: 8px; margin-right: 5px; }
input[type="submit"] { cursor: pointer; background-color: #007bff; color: white; border: none; border-radius: 4px; }
input[type="submit"]:hover { background-color: #0056b3; }
</style>
</head>
<body>
<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> <!-- 假设JavaScript代码在app.js中 -->
</body>
</html>我们将从一个公共API(例如COVID-19 API)获取国家疫情数据。关键在于将获取到的Countries数组存储在一个全局变量中,以便后续的搜索和过滤操作能够访问到完整的数据集。
立即学习“Java免费学习笔记(深入)”;
// app.js
// 用于存储从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表格中。这个函数可以接受一个可选的参数,用于指定要展示的数据子集(例如,搜索结果)。
// app.js (接上文)
/**
* 将国家数据显示到表格中
* @param {string} searchTerm - 可选的搜索关键词,用于过滤国家名称
*/
const _DisplayCountries = (searchTerm = "") => {
const tbody = document.querySelector("#tbody");
tbody.innerHTML = ``; // 清空现有表格内容
// 根据搜索词过滤数据,如果searchTerm为空,则显示所有数据
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>
`;
});
};在_DisplayCountries函数中,我们对Date字段进行了格式化,使其更具可读性。
现在,我们将为搜索按钮添加事件监听器。当用户点击搜索按钮时,我们将获取搜索框中的值,并将其传递给_DisplayCountries函数,从而实现数据的过滤和更新。
// app.js (接上文)
// 获取搜索按钮和输入框
const searchInput = document.querySelector("#myInput");
const searchButton = document.querySelector("#mySubmit");
// 为搜索按钮添加点击事件监听器
searchButton.addEventListener("click", () => {
const searchTerm = searchInput.value.trim(); // 获取并去除输入值两端的空白
_DisplayCountries(searchTerm); // 调用显示函数,传入搜索词
});
// 也可以为输入框添加 'input' 事件监听器,实现实时搜索
searchInput.addEventListener("input", () => {
const searchTerm = searchInput.value.trim();
_DisplayCountries(searchTerm);
});这里我们同时为搜索按钮的click事件和搜索输入框的input事件添加了监听器。这意味着用户可以点击按钮进行搜索,也可以在输入时实时看到结果更新,这通常能提供更好的用户体验。
将上述所有JavaScript代码整合到一个文件中(例如app.js),并确保HTML文件正确引用它。
// app.js
let countriesData = [];
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 _DisplayCountries = (searchTerm = "") => {
const tbody = document.querySelector("#tbody");
tbody.innerHTML = ``;
const filteredCountries = countriesData.filter(country =>
country.Country.toLowerCase().includes(searchTerm.toLowerCase())
);
if (filteredCountries.length === 0 && searchTerm !== "") {
tbody.innerHTML = `<tr><td colspan="8" style="text-align: center;">没有找到匹配 "${searchTerm}" 的国家。</td></tr>`;
return;
}
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>
`;
});
};
getdata();
const searchInput = document.querySelector("#myInput");
const searchButton = document.querySelector("#mySubmit");
searchButton.addEventListener("click", () => {
const searchTerm = searchInput.value.trim();
_DisplayCountries(searchTerm);
});
searchInput.addEventListener("input", () => {
const searchTerm = searchInput.value.trim();
_DisplayCountries(searchTerm);
});// 使用正则表达式进行搜索 // let regex = new RegExp(searchTerm, "i"); // "i" 标志表示不区分大小写 // countriesData.filter(country => country.Country.match(regex))
通过本教程,我们学习了如何构建一个基于API数据的动态搜索功能。关键在于高效地获取并存储数据,利用filter()方法进行客户端筛选,并通过专门的函数动态更新UI。这种模式不仅适用于表格数据,也适用于任何需要动态过滤和展示列表数据的场景,为用户提供了灵活且响应迅速的数据探索体验。
以上就是JavaScript实现动态API数据搜索与表格动态展示教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号