如何在start.html展示news.html中近10天的guidediv容器?
实现start.html展示news.html近10天新闻的可行方案
当然可行,以下是几种实用的实现方式:
一、前端JavaScript实现(同源站点适用)
如果start.html和news.html属于同一域名、端口、协议(同源环境),可以直接用JS读取并筛选新闻:
- 在
start.html中添加新闻展示容器:
<div id="recent-news"></div>
- 编写JS逻辑获取并筛选新闻:
// 计算10天前的日期 const cutoffDate = new Date(); cutoffDate.setDate(cutoffDate.getDate() - 10); // 加载news.html内容 fetch('news.html') .then(res => res.text()) .then(html => { // 解析HTML内容 const tempDoc = new DOMParser().parseFromString(html, 'text/html'); const allNews = tempDoc.querySelectorAll('.guidediv'); const newsContainer = document.getElementById('recent-news'); // 筛选近10天的新闻并渲染 allNews.forEach(newsDiv => { const newsDate = new Date(newsDiv.dataset.date); if (newsDate >= cutoffDate) { newsContainer.appendChild(newsDiv.cloneNode(true)); } }); }) .catch(err => console.log('加载新闻出错:', err));
注意:如果两个页面跨域(不同域名),直接用fetch会触发浏览器跨域限制,需要后端配合处理。
二、后端渲染方案(通用场景)
如果存在跨域问题,或者需要更好的性能,推荐用后端处理:
- 后端读取
news.html的内容,解析所有.guidediv的data-date属性,筛选出近10天的新闻片段。 - 在渲染
start.html时,直接将筛选后的新闻内容插入到页面指定位置。 - 或者后端提供一个接口,返回结构化的近10天新闻数据,前端调用接口渲染。
三、静态站点生成方案
如果是静态网站,可以用静态生成工具(如Jekyll、Hugo)优化流程:
- 将新闻内容用Markdown等统一格式单独管理,而非直接写在
news.html中。 - 配置工具在构建阶段自动筛选近10天的新闻,直接生成到
start.html对应位置。
内容的提问来源于stack exchange,提问作者bkoenig
相关产品推荐
相关产品推荐

