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

Chart.js中使用字符串数组自定义Tooltip标签失败求助

解决Chart.js中自定义Tooltip标签显示异常的问题

我仔细看了你的代码,问题核心出在Tooltip标题回调函数的逻辑处理上,下面帮你拆解问题并给出可行的解决方案:

问题根源分析

  • 无循环版本:直接返回整个tooltipsLabel数组,Chart.js会把数组的每一项都作为Tooltip的标题行展示,所以每个Tooltip都会显示所有城市名称。
  • 带循环的版本:在for循环里直接执行return tooltipsLabel[i],第一次循环(i=0)就会返回结果,导致所有Tooltip都只显示第一个标签Dhaka,完全没用到当前hover数据的索引。

正确解决方案

我们需要利用tooltipItem参数里的当前数据索引,匹配tooltipsLabel中对应的标签。修改Tooltip的回调配置即可:

tooltips: {
  mode: 'index',
  intersect: true,
  callbacks: {
    title: function (tooltipItem, data) {
      // 单数据集场景下,取第一个tooltip项的索引即可
      const currentIndex = tooltipItem[0].index;
      // 返回对应索引的自定义标签
      return tooltipsLabel[currentIndex];
    }
  }
}

完整修改后的代码

JavaScript部分

var tooltipsLabel = ['Dhaka','Rajshahi','NewYork','London']
var chartList = [5,6,7,8];
function chart(){
 var ctx = document.getElementById("myChart").getContext('2d');
 var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
   labels: ["Red", "Blue","green","Yellow"],
   datasets: [{
    label: '# of Votes',
    data: chartList,
    backgroundColor: [
     'rgba(255, 99, 132, 0.2)',
     'rgba(54, 162, 235, 0.2)',
     'rgba(255, 99, 132, 0.2)',
     'rgba(54, 162, 235, 0.2)',
    ],
    borderColor: [
     'rgba(255,99,132,1)',
     'rgba(54, 162, 235, 1)',
     'rgba(255,99,132,1)',
     'rgba(54, 162, 235, 1)',
    ],
    borderWidth: 1
   }]
  },
  options: {
   scales: {
    yAxes: [{ ticks: { beginAtZero:true } }]
   },
   tooltips: {
    mode: 'index',
    intersect: true,
    callbacks: {
     title: function (tooltipItem, data) {
       const currentIndex = tooltipItem[0].index;
       return tooltipsLabel[currentIndex];
     }
    }
   }
  }
 });
}
chart();

HTML部分

<html>
<head>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
 <div class="row">
  <div class="col-lg-4">
   <canvas id="myChart" width="100" height="100"></canvas>
  </div>
  <div class="col-lg-4"><canvas id="pieChart" width="100" height="100"></canvas></div>
 </div>
 <script>
 </script>
</body>
</html>

逻辑说明

在Chart.js的Tooltip回调中,tooltipItem是包含当前Tooltip所有数据项的数组(当设置mode: 'index'时,会展示同一索引下的所有数据集内容)。对于你的单数据集场景,我们只需要取数组第一个元素的index属性,就能拿到当前hover的数据点对应的索引,再用这个索引去tooltipsLabel数组中取出对应的城市名称即可。

修改后,每个柱状条的Tooltip都会显示对应的自定义标签,不会再出现显示全部标签或固定第一个标签的问题。

内容的提问来源于stack exchange,提问作者Abdullah Al Mamun

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:45:03