如何用document.querySelectorAll存储类元素至Web Storage并在另一页面展示
解决方案
失效代码核心问题
- 函数名用了JavaScript内置对象
Array,造成命名冲突 - 直接把
NodeList对象存进localStorage,localStorage只能存字符串,得存实际HTML内容 - 对
document.querySelectorAll()返回的集合直接赋值innerHTML/href,这类集合不能直接操作,必须遍历处理 - 循环里反复覆盖同一个localStorage键值,最后只剩最后一个元素的内容
首页代码(收集并存储文章预告)
window.onload = function collectTopicPosts() { // 检查Web Storage支持 if (typeof(Storage) !== "undefined") { // 获取所有.EV类的文章预告元素 const postPreviews = document.querySelectorAll('.EV'); // 提取每个元素的HTML内容,转成数组 const previewContents = Array.from(postPreviews).map(item => item.innerHTML); // 数组转字符串存入localStorage localStorage.setItem('EVPostPreviews', JSON.stringify(previewContents)); // 提取每个预告对应的链接(假设每个.EV里有类为.post-link的链接,按需调整) const postLinks = Array.from(postPreviews).map(item => item.querySelector('.post-link').href); localStorage.setItem('EVPostLinks', JSON.stringify(postLinks)); } else { console.log('浏览器不支持Web Storage,无法同步文章预告'); } };
专题页代码(读取并展示文章预告)
window.onload = function displayTopicPosts() { if (typeof(Storage) !== "undefined") { // 读取存储的预告内容和链接 const storedPreviews = localStorage.getItem('EVPostPreviews'); const storedLinks = localStorage.getItem('EVPostLinks'); if (storedPreviews && storedLinks) { const previewContents = JSON.parse(storedPreviews); const postLinks = JSON.parse(storedLinks); // 获取专题页的容器(类为.EV2) const container = document.querySelector('.EV2'); container.innerHTML = ''; // 清空原有内容 // 遍历创建每个预告元素,添加间距 previewContents.forEach((content, index) => { // 创建文章预告容器 const postElement = document.createElement('div'); postElement.innerHTML = content; // 给链接赋值(类为.EV3的元素) const linkElement = postElement.querySelector('.EV3'); if (linkElement) linkElement.href = postLinks[index]; container.appendChild(postElement); // 最后一个元素不添加间距div if (index !== previewContents.length - 1) { const spacer = document.createElement('div'); spacer.style.marginBottom = '20px'; // 可自定义间距大小 container.appendChild(spacer); } }); } else { document.querySelector('.EV2').textContent = '暂无相关文章预告'; } } else { document.querySelector('.EV2').textContent = '浏览器不支持Web Storage,无法加载文章预告'; } };
注意事项
- 确保首页
.EV、专题页.EV2、链接.EV3的类名和你的DOM结构完全匹配 - localStorage只能同域共享,若首页和专题页域名不同,这套方案不适用
- 间距div的样式可以改成自定义类名,方便通过CSS统一控制,不用内联样式
内容的提问来源于stack exchange,提问作者Scanditranslate
相关产品推荐
相关产品推荐

