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

如何通过DOM实现点击按钮将菜品添加到折叠面板的收藏区?

问题:如何将菜品添加到折叠面板的收藏区域

我的「Add to favs」按钮能在控制台正常触发,但不知道怎么把菜品添加到展开的折叠面板内的收藏区域。该折叠面板内容默认隐藏,目标容器为类名为.content的div。已实现fetchMeal函数获取菜品数据并生成添加按钮,尝试过类似待办清单的document.createElement方法但无效,现需完善addRemoveToFavList函数。


现有代码

HTML结构

<button type="button" class="collapsible">Open Collapsible</button>
<div class="content">
  <p>dskshf</p>
</div>

JS代码片段

const fetchMeal = async (query) => {
  const response = await fetch(`https://www.themealdb.com/api/json/v1/1/search.php?s=${query}`);
  const response2 = await response.json();
  response2.meals.forEach(meal => {
    const newdiv = document.createElement('div');
    newdiv.classList.add('recipe');
    newdiv.innerHTML = `
    <img src = "${meal.strMealThumb}">
    <h2>${meal.strMeal}</h2>
    <p>${meal.strCategory} </p>
    `;

    // 收藏按钮部分
    const FavBtn = document.createElement('button');
    FavBtn.textContent = "Add to favs";
    newdiv.appendChild(FavBtn);
    FavBtn.addEventListener('click', () => {
      addRemoveToFavList(meal, FavBtn); // 传入按钮,方便切换文字状态
    });

    // 把生成的菜品卡片添加到页面(这里假设添加到body,可根据实际调整)
    document.body.appendChild(newdiv);
  });
};

CSS样式

.collapsible {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 10%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}
.active, .collapsible:hover {
  background-color: #c9a5a5;
}
/* 折叠面板内容默认隐藏 */
.content {
  padding: 0 18px;
  display: none;
  overflow: hidden;
  background-color: #f1f1f1;
}
/* 收藏菜品的样式(可选) */
.fav-meal {
  margin: 12px 0;
  padding: 10px;
  border-bottom: 1px solid #ddd;
}

解决方案

1. 先完善折叠面板的展开/收起功能

首先给折叠按钮绑定事件,实现内容的显示切换:

// 折叠面板逻辑
const collapsibleBtn = document.querySelector('.collapsible');
collapsibleBtn.addEventListener('click', function() {
  this.classList.toggle('active');
  const content = document.querySelector('.content');
  content.style.display = content.style.display === 'block' ? 'none' : 'block';
});

2. 实现addRemoveToFavList函数

这个函数要完成「检查重复、添加/移除菜品、切换按钮状态」三个核心动作:

function addRemoveToFavList(meal, btn) {
  const favContainer = document.querySelector('.content');
  // 用菜品ID作为唯一标识,避免重复添加
  const mealUniqueId = meal.idMeal;
  const existingMeal = favContainer.querySelector(`[data-meal-id="${mealUniqueId}"]`);

  if (existingMeal) {
    // 若已存在,移除该菜品并切换按钮文字
    existingMeal.remove();
    btn.textContent = "Add to favs";
  } else {
    // 创建收藏菜品的DOM元素
    const favMealCard = document.createElement('div');
    favMealCard.classList.add('fav-meal');
    favMealCard.dataset.mealId = mealUniqueId; // 标记唯一ID
    favMealCard.innerHTML = `
      <img src="${meal.strMealThumb}" style="width: 80px; height: 80px; object-fit: cover;">
      <h3>${meal.strMeal}</h3>
      <p>${meal.strCategory}</p>
      <button class="remove-fav-btn">移除收藏</button>
    `;

    // 给移除按钮绑定事件
    favMealCard.querySelector('.remove-fav-btn').addEventListener('click', () => {
      favMealCard.remove();
      btn.textContent = "Add to favs";
    });

    // 将收藏菜品添加到目标容器
    favContainer.appendChild(favMealCard);
    btn.textContent = "Remove from favs";
  }
}

关键说明

  • 用meal.idMeal作为唯一标识,彻底避免重复添加同一菜品
  • 把按钮元素传入函数,方便直接切换按钮文字状态
  • 给收藏的菜品单独添加移除按钮,提升交互体验
  • 无论折叠面板是否展开,只要DOM元素存在就能完成添加操作,不影响功能

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 10:04:52