You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Vanilla JavaScript实现菜谱收藏本地存储与页面展示?

问题解决:菜谱收藏功能完整实现方案

原代码核心问题

  1. 仅传递并存储了菜谱标题,未包含图片、URL等所需数据
  2. 缺少getFromLocalStorage函数实现(原代码调用了但未定义)
  3. 收藏页无读取LocalStorage并渲染内容的逻辑
  4. alert语句存在模板字符串语法错误(缺少引号包裹)

1. 完善index.html的收藏存储逻辑

替换原代码为以下实现,支持存储完整菜谱数据并判断重复:

// 定义LocalStorage键名(统一管理避免拼写错误)
const favListKey = 'recipeFavourites';

// 补全LocalStorage读取函数
function getFromLocalStorage(key) {
  const storedData = localStorage.getItem(key);
  return storedData ? JSON.parse(storedData) : null;
}

function saveToLocalStorage(key, value) {
  localStorage.setItem(key, JSON.stringify(value));
}

// 修改收藏函数,接收完整菜谱对象
function addToFavourites(recipe) {
  const favourites = getFromLocalStorage(favListKey) || [];
  
  // 用标题判断是否已收藏(若API返回唯一ID,用ID判断更准确)
  const isAlreadySaved = favourites.some(item => item.label === recipe.label);

  if (!isAlreadySaved) {
    // 存入包含图片、标题、URL的完整对象
    favourites.push({
      label: recipe.label,
      image: recipe.image,
      url: recipe.url
    });
    saveToLocalStorage(favListKey, favourites);
    alert(`${recipe.label} 已添加到收藏!`);
  } else {
    alert(`${recipe.label} 已经在收藏列表中了!`);
  }
}

// 绑定收藏图标点击事件示例(需根据你的渲染逻辑调整)
// 假设你循环渲染菜谱卡片时:
// recipes.forEach(recipe => {
//   const card = document.createElement('div');
//   // ... 渲染菜谱图片、标题等内容
//   const favBtn = document.createElement('button');
//   favBtn.className = 'fav-icon';
//   favBtn.addEventListener('click', () => addToFavourites(recipe));
//   card.appendChild(favBtn);
//   document.getElementById('recipe-list').appendChild(card);
// });

2. 实现favourite.html的收藏列表渲染

在favourite.html中添加以下代码,读取LocalStorage并展示收藏内容:

<!-- 先在页面中添加承载收藏内容的容器 -->
<div id="favourite-container"></div>

<script>
const favListKey = 'recipeFavourites';

function getFromLocalStorage(key) {
  const storedData = localStorage.getItem(key);
  return storedData ? JSON.parse(storedData) : null;
}

// 渲染收藏列表函数
function renderFavourites() {
  const favourites = getFromLocalStorage(favListKey) || [];
  const container = document.getElementById('favourite-container');

  // 无收藏时显示提示
  if (favourites.length === 0) {
    container.innerHTML = '<p>你还没有收藏任何菜谱</p>';
    return;
  }

  // 生成HTML字符串并渲染
  const favHTML = favourites.map(recipe => `
    <div class="fav-recipe-card">
      <img src="${recipe.image}" alt="${recipe.label}" width="160">
      <h3>${recipe.label}</h3>
      <a href="${recipe.url}" target="_blank">查看菜谱详情</a>
    </div>
  `).join('');

  container.innerHTML = favHTML;
}

// 页面加载完成后自动渲染
window.addEventListener('DOMContentLoaded', renderFavourites);
</script>

关键注意事项

  • 确保绑定收藏按钮点击事件时,传递的是包含label、image、url的完整菜谱对象,而非仅标题
  • 若API返回菜谱的唯一ID(如recipe.id),建议用ID判断是否已收藏,避免同名菜谱重复存储
  • 可根据需求为收藏卡片添加自定义CSS样式,优化展示效果

内容的提问来源于stack exchange,提问作者Avic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 04:57:28