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

如何隐藏/移除Mapbox GL JS表格弹窗中的空属性对应行

实现方案

你可以通过三元表达式动态判断字段是否为空,仅当字段为有效值时才拼接对应的表格行HTML代码即可,同时修正了原代码中Information值前多余的<符号错误:

const popup = new mapboxgl.Popup({offset: [0, -15]})
.setMaxWidth("auto")
.setLngLat(feature.geometry.coordinates)
.setHTML(
`<table>
  <tr>
    <td>City Name</td>
    <td>${feature.properties.City}</td>
  </tr>
  ${feature.properties.Information ? `
  <tr>
    <td>Information</td>
    <td>${feature.properties.Information}</td>
  </tr>
  ` : ''}
</table>`)
.addTo(map);

如果后续有更多字段需要做相同的空值隐藏逻辑,可以封装通用生成函数降低重复代码:

  • 先定义表格行生成函数,传入表头名称和字段值,空值直接返回空字符串
  • 所有需要动态展示的字段都调用该函数生成对应行,后续新增字段只需加一行调用代码即可
// 通用表格行生成函数,可自定义空值判断规则
function getTableRow(label, value) {
  if (value === null || value === undefined || value === '') return ''
  return `<tr><td>${label}</td><td>${value}</td></tr>`
}

// 弹窗调用示例
const popup = new mapboxgl.Popup({offset: [0, -15]})
.setMaxWidth("auto")
.setLngLat(feature.geometry.coordinates)
.setHTML(
`<table>
  ${getTableRow('City Name', feature.properties.City)}
  ${getTableRow('Information', feature.properties.Information)}
</table>`)
.addTo(map);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 05:36:04