You need to enable JavaScript to run this app. 点击Chart.js环形图指定区域时如何获取对应标签名与数值
优惠活动
大模型
产品
解决方案
定价
更多

点击Chart.js环形图指定区域时如何获取对应标签名与数值

解决方案

Chart.js 的 onClick 回调支持3个入参,我们可以通过第二个参数activeElements获取点击的环形切片对应数据:

  • 第一个参数:原生点击事件对象
  • 第二个参数:当前点击命中的图表元素数组
  • 第三个参数:当前图表实例

你可以直接替换原有onClick部分的代码,以下是完整修改后的逻辑:

onClick: (e, activeElements) => {
    // 判断是否点击到了环形图的切片
    if (activeElements.length > 0) {
        // 获取点击切片的索引
        const clickedIndex = activeElements[0].index;
        // 拿取对应标签和数值
        const selectedLabel = labels[clickedIndex];
        const selectedValue = numbers[clickedIndex];
        // 把值填充到模态框中,你需要提前在模态框HTML里加对应ID的元素
        document.getElementById('selectedLabel').textContent = selectedLabel;
        document.getElementById('selectedValue').textContent = selectedValue;
        // 弹出模态框
        $('#bookingInfoModal').modal('show');
    }
},

配套模态框HTML示例

你可以在你的Blade模板里加入模态框的结构,示例如下:

<div class="modal fade" id="bookingInfoModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">预订数据详情</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <p>状态:<span id="selectedLabel"></span></p>
        <p>数量:<span id="selectedValue"></span></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
      </div>
    </div>
  </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 23:24:03