昨天已經加入收藏功能,現在使用者可以將喜歡的食譜保存起來。
但收藏之後,還需要有一個地方可以查看這些內容。
因此,今天要建立「我的收藏」區域。
一、建立收藏區域
在 HTML 中加入:
<section>
<h2>❤️ 我的收藏</h2>
<div id="favoriteList"></div>
</section>
二、讀取收藏資料
在 JavaScript 中加入:
const favoriteList =
document.querySelector("#favoriteList");
function displayFavorites() {
const favorites = getFavorites();
favoriteList.replaceChildren();
if (favorites.length === 0) {
favoriteList.textContent =
"目前還沒有收藏的食譜。";
return;
}
favorites.forEach(function (recipe) {
const item = document.createElement("div");
item.className = "recipe-card";
const title = document.createElement("h3");
title.textContent = recipe.name;
const removeBtn = document.createElement("button");
removeBtn.textContent = "取消收藏";
removeBtn.addEventListener("click", function () {
const updated = getFavorites().filter(
item => item.name !== recipe.name
);
localStorage.setItem(
"favorites",
JSON.stringify(updated)
);
displayFavorites();
});
item.append(title, removeBtn);
favoriteList.appendChild(item);
});
}
最後,在 JavaScript 載入時呼叫:
displayFavorites();
這樣就能顯示目前保存的食譜,也能取消收藏。
三、今天的成果
今天完成收藏清單的基本功能,包含讀取收藏、顯示食譜和取消收藏。
目前 AI Recipe 已經有輸入、推薦、篩選和收藏等功能,逐漸接近完整網站。
接下來要開始改善手機版的顯示效果,讓不同裝置都能方便使用。