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

如何基于数组中唯一board_id实例创建HTML按钮元素

解决多对多查询结果中生成唯一board_id按钮的方案

核心思路

先对返回的JSON数据做去重处理,提取出唯一的board_id对应的条目,再基于这些唯一条目生成按钮元素。

具体实现代码

以下是完整的fetch处理流程,包含数据去重和按钮生成:

fetch('你的PHP接口路径')
  .then(res => res.json())
  .then(rawData => {
    // 1. 去重:用Map存储唯一的board条目,key为board_id
    const uniqueBoardMap = new Map();
    rawData.forEach(item => {
      // 仅当Map中不存在该board_id时才添加
      if (!uniqueBoardMap.has(item.board_id)) {
        uniqueBoardMap.set(item.board_id, item);
      }
    });

    // 把Map中的值转为数组,方便遍历
    const uniqueBoards = Array.from(uniqueBoardMap.values());

    // 2. 获取目标容器并清空(可选,防止重复渲染)
    const wrapper = document.getElementById('你的容器ID');
    wrapper.innerHTML = '';

    // 3. 遍历唯一数据,生成按钮插入容器
    uniqueBoards.forEach(board => {
      // 模板字符串自定义按钮内容,可根据实际字段调整
      const buttonTemplate = `
        <button class="board-button" data-board-id="${board.board_id}">
          看板:${board.board_name || board.board_id}
        </button>
      `;
      wrapper.insertAdjacentHTML('beforeend', buttonTemplate);
    });
  })
  .catch(err => console.log('数据请求失败:', err));

简化版(仅需board_id时)

如果不需要保留board的其他信息,用Set去重更简洁:

fetch('你的PHP接口路径')
  .then(res => res.json())
  .then(rawData => {
    // 提取所有唯一的board_id
    const uniqueIds = new Set(rawData.map(item => item.board_id));
    const wrapper = document.getElementById('你的容器ID');
    wrapper.innerHTML = '';

    Array.from(uniqueIds).forEach(id => {
      const button = `<button data-id="${id}">看板 ${id}</button>`;
      wrapper.insertAdjacentHTML('beforeend', button);
    });
  });

注意事项

  • 如果需要给按钮绑定点击事件,可在生成后逐个绑定,或用事件委托(更高效):
    // 事件委托示例
    wrapper.addEventListener('click', (e) => {
      if (e.target.classList.contains('board-button')) {
        const boardId = e.target.dataset.boardId;
        console.log('点击了看板:', boardId);
        // 执行后续逻辑
      }
    });
    
  • 清空wrapper.innerHTML是为了避免多次请求时重复添加按钮,若需要保留原有内容,可去掉这一步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:21:01