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

ChartJS点击饼图扇区触发弹窗展示对应扇区标签名称的实现问题

ChartJS 饼图点击获取扇区标签方案

解决代码

直接替换你的onClick配置即可:

responsive: false,
onClick : (event, items, chartInstance) => {
    // 仅在点击到扇区时触发逻辑,避免点击空白区域报错
    if (!items.length) return
    const activeSector = items[0]
    // 兼容新旧版本ChartJS的扇区索引属性
    const sectorIndex = activeSector.index ?? activeSector._index
    // 提取悬停显示的扇区标签
    const sectorLabel = chartInstance.data.labels[sectorIndex]
    alert(sectorLabel)
}

逻辑说明

  • items是点击命中的扇区元素集合,饼图单次点击只会命中一个扇区,直接取第一个元素即可
  • 不同版本ChartJS的索引属性命名有差异:新版本为index,你提供的结构里的旧版本为_index,用空值合并运算符可适配两种情况
  • 饼图默认的悬停标签统一存放在图表实例的data.labels数组中,和扇区的索引一一对应,直接按索引取值即可
    如果你使用了自定义的标签字段存放在数据集里,只需调整取值逻辑为chartInstance.data.datasets[activeSector.datasetIndex ?? activeSector._datasetIndex].自定义标签字段[sectorIndex]即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 16:24:03