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

如何为Firestore自动生成表格的Titulo列分配不同Href

解决Firestore数据生成表格中动态设置不同href的问题

你可以通过根据标题动态匹配对应URL的方式来解决这个问题,不用硬编码固定的href。这里有两种实用的方案,根据你的需求选择:

方案1:条件判断(适合少量标题的场景)

直接在遍历Firestore文档时,根据oferta.titulo的值判断对应的href:

const ofertaList = document.querySelector('#ofertaLista');
const setupOferta = (data) => {
 let html = '';
 data.forEach(doc => {
 const oferta = doc.data();
 // 根据标题设置对应的href
 let itemHref = '#'; // 默认链接,可根据需求修改
 if (oferta.titulo === 'Historia del arte') {
   itemHref = 'historia.html';
 } else if (oferta.titulo === 'Matematicas 1') {
   itemHref = 'matematicas.html';
 }
 const td =`
 <tr>
 <td><a href="${itemHref}">${oferta.titulo}</a></td>
 <td>${oferta.tipo}</td>
 <td>${oferta.fecha}</td>
 <td>${oferta.areaConocimiento}</td>
 <td>${oferta.cupoLimitado}</td>
 </tr>
 `;
 html += td
 });
 ofertaList.innerHTML = html;
}
db.collection('oferta').get().then((snapshot) =>{
 setupOferta(snapshot.docs)
});

方案2:映射对象(适合需要扩展更多标题的场景)

如果以后要添加更多标题对应的链接,用对象映射会更简洁易维护:

const ofertaList = document.querySelector('#ofertaLista');
// 先创建标题和URL的映射表
const titleUrlMap = {
  'Historia del arte': 'historia.html',
  'Matematicas 1': 'matematicas.html',
  // 后续新增标题直接在这里加键值对即可
};
const setupOferta = (data) => {
 let html = '';
 data.forEach(doc => {
 const oferta = doc.data();
 // 从映射表中获取对应的URL,找不到则用默认值
 const itemHref = titleUrlMap[oferta.titulo] || '#';
 const td =`
 <tr>
 <td><a href="${itemHref}">${oferta.titulo}</a></td>
 <td>${oferta.tipo}</td>
 <td>${oferta.fecha}</td>
 <td>${oferta.areaConocimiento}</td>
 <td>${oferta.cupoLimitado}</td>
 </tr>
 `;
 html += td
 });
 ofertaList.innerHTML = html;
}
db.collection('oferta').get().then((snapshot) =>{
 setupOferta(snapshot.docs)
});

原理说明

原来的代码中href是硬编码的固定值,所以所有单元格的链接都相同。现在通过动态匹配每个文档的titulo字段,为不同标题分配对应的URL,就能实现每个<td>的链接各不相同的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 22:14:08