如何用原生JS实现HTML列表页到详情页的对应内容展示?
实现方案
一、调整列表页(posts.html)的跳转逻辑
如果你的列表页已经完成文章列表渲染,只需要给每个标题添加带ID参数的跳转链接,把文章ID通过URL传递给详情页:
<div id="posts-list"></div> <script> // 基于你已有的列表渲染代码补充跳转逻辑 fetch('https://jsonplaceholder.typicode.com/posts') .then(res => res.json()) .then(posts => { const listContainer = document.getElementById('posts-list'); posts.forEach(post => { const postItem = document.createElement('div'); // 核心:通过URL参数传递文章ID const titleLink = document.createElement('a'); titleLink.href = `detail.html?id=${post.id}`; titleLink.textContent = post.title; const excerpt = document.createElement('p'); excerpt.textContent = post.body.substring(0, 50) + '...'; // 可选:显示内容摘要 postItem.appendChild(titleLink); postItem.appendChild(excerpt); listContainer.appendChild(postItem); }); }); </script>
二、完成详情页(detail.html)的功能
详情页需要完成三个核心步骤:提取URL中的文章ID、请求对应文章数据、渲染内容到页面,完整代码如下:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>文章详情</title> </head> <body> <div id="post-detail"></div> <script> // 1. 从URL中提取文章ID function getPostId() { const params = new URLSearchParams(window.location.search); return params.get('id'); } const postId = getPostId(); if (!postId) { document.getElementById('post-detail').textContent = '无效的文章ID'; return; } // 2. 请求对应ID的文章数据 fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`) .then(res => { if (!res.ok) throw new Error('文章不存在'); return res.json(); }) .then(post => { // 3. 渲染文章内容 const detailContainer = document.getElementById('post-detail'); const titleEl = document.createElement('h1'); titleEl.textContent = post.title; const contentEl = document.createElement('p'); contentEl.textContent = post.body; detailContainer.appendChild(titleEl); detailContainer.appendChild(contentEl); }) .catch(err => { document.getElementById('post-detail').textContent = err.message; }); </script> </body> </html>
关键说明
- 用
URLSearchParams解析URL参数,是原生JS处理查询参数的标准方法,兼容性覆盖绝大多数现代浏览器 - 跳转时通过
detail.html?id=xxx传递ID,详情页拿到ID后请求单篇文章的接口 - 加入了基础错误处理,避免ID无效或请求失败时页面空白
内容的提问来源于stack exchange,提问作者darkman106
相关产品推荐
相关产品推荐

