如何根据点击的a标签内部文本,为跳转的目标页渲染对应内容
解决方法
你目前的问题是只把全部分类存入了localStorage,没有记录用户点击的具体分类,只要在跳转前记录选中的分类标识即可,这里提供两种可直接落地的实现方案:
方案1:URL查询参数传值(更推荐,支持页面刷新、链接分享场景)
直接把选中的分类名拼接在跳转链接的查询参数中,不需要依赖localStorage:
import { fetchData, createListItem} from "../Utils.js"; // List Categories const createHeroCategories = () => fetchData("https://www.themealdb.com/api/json/v1/1/categories.php") .then((data) => { data.categories.forEach((category) => createListItem(".categories-list", category["strCategory"], "category-item") ); Array.from(document.getElementsByClassName('category-item')).forEach(element => { let temp = element.innerText; // 给跳转链接拼接分类查询参数,用encodeURIComponent处理特殊字符 element.innerHTML = `<a href="./pages/categories.html?category=${encodeURIComponent(temp)}">${temp}</a>`; }) }) .catch((e) => alert(e.message)); export {createHeroCategories};
然后在categories.html页面的JS中读取查询参数即可:
// categories.html 页面的JS代码 // 解析URL中的查询参数 const getQueryParam = (key) => { const urlParams = new URLSearchParams(window.location.search); return decodeURIComponent(urlParams.get(key)); } const selectedCategory = getQueryParam('category'); // 接下来用selectedCategory去拉取对应分类的内容即可
方案2:localStorage存选中标识
如果不想参数暴露在URL中,可以在用户点击分类时,把选中的分类存入localStorage的固定字段:
import { fetchData, createListItem} from "../Utils.js"; // List Categories const createHeroCategories = () => fetchData("https://www.themealdb.com/api/json/v1/1/categories.php") .then((data) => { data.categories.forEach((category) => createListItem(".categories-list", category["strCategory"], "category-item") ); Array.from(document.getElementsByClassName('category-item')).forEach(element => { let temp = element.innerText; const aTag = document.createElement('a'); aTag.href = "./pages/categories.html"; aTag.innerText = temp; // 绑定点击事件,点击时存储选中的分类 aTag.addEventListener('click', () => { localStorage.setItem('selectedCategory', temp); }) element.appendChild(aTag); }) }) .catch((e) => alert(e.message)); export {createHeroCategories};
在categories.html页面读取:
// categories.html 页面的JS代码 const selectedCategory = localStorage.getItem('selectedCategory'); // 读取后可以按需删除这个存储项避免后续干扰 // localStorage.removeItem('selectedCategory'); // 后续拉取对应分类内容即可
内容的提问来源于stack exchange,提问作者OrcunSelbasan
相关产品推荐
相关产品推荐

