iT邦幫忙

2026 iThome 鐵人賽

0
自我挑戰組

AI Recipe — AI 智慧食譜推薦系統系列 第 23 篇

我的收藏食譜頁面

  • 分享至 

  • xImage
  •  

昨天已經加入收藏功能,現在使用者可以將喜歡的食譜保存起來。

但收藏之後,還需要有一個地方可以查看這些內容。

因此,今天要建立「我的收藏」區域。

一、建立收藏區域

在 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 已經有輸入、推薦、篩選和收藏等功能,逐漸接近完整網站。

接下來要開始改善手機版的顯示效果,讓不同裝置都能方便使用。


上一篇
收藏我的食譜
下一篇
手機也能使用!
系列文
AI Recipe — AI 智慧食譜推薦系統 共 30 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言