
本文档将指导您如何使用 Pokémon API,在点击“更多信息”按钮后,将特定 Pokémon 的详细信息展示在一个新的 HTML 页面中。我们将利用 URL 查询参数传递 Pokémon 的 ID,并在新页面中获取并显示这些信息。
通过 URL 查询参数传递 Pokémon ID
为了在新页面中显示特定 Pokémon 的详细信息,我们需要一种方法来告诉 details.html 页面要显示哪个 Pokémon。最常用的方法之一是使用 URL 查询参数。
在 index.html 的 App.js 文件中,修改 seeDetail 函数,将 Pokémon 的 ID 作为查询参数添加到 details.html 的 URL 中:
function seeDetail(id){
window.open('details.html?id=' + id, '_blank');
}现在,当点击“更多信息”按钮时,details.html 页面将在新的标签页中打开,并且 URL 将包含 Pokémon 的 ID,例如:details.html?id=25。
在 details.html 中获取并显示 Pokémon 详细信息
接下来,我们需要在 details.html 页面中获取 URL 查询参数中的 Pokémon ID,并使用该 ID 从 Pokémon API 获取详细信息。
在 details.html 页面中,添加以下 JavaScript 代码:
Pokemon Details
这段代码首先获取 more-details 元素的引用,该元素将用于显示 Pokémon 详细信息。然后,定义了一个 detailsPokemon 函数,该函数接收一个 Pokémon 对象并将其详细信息添加到 more-details 元素中。
最重要的是,代码使用 new URLSearchParams(location.search).get('id') 从 URL 查询参数中获取 Pokémon ID。然后,使用该 ID 从 Pokémon API 获取 Pokémon 详细信息,并调用 detailsPokemon 函数来显示这些信息。
完整示例
以下是完整的 index.html 和 details.html 文件:
index.html
Pokemon List
details.html
Pokemon Details
Pokemon Details
总结
通过使用 URL 查询参数,我们能够轻松地将 Pokémon ID 从 index.html 传递到 details.html,并在新页面中显示特定 Pokémon 的详细信息。这种方法简单有效,并且易于理解和实现。 记住要确保你的 details.html 文件能够正确地从 URL 中提取 ID 并使用它来获取数据。










