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

如何获取同一元素内ct-series类之后的下一个类名?

解决方案

错误原因

你原代码中使用的next()方法是用来查找当前选中元素的下一个同级DOM节点,无法提取同一元素上的类属性,因此返回结果不符合预期。

实现代码

单个ct-series元素场景

// 定位目标ct-series元素
const ctSeriesEl = $(this).closest('.ct-chart-bar').find('.ct-series');
// 拆分类属性为数组
const classArr = ctSeriesEl.attr('class').split(/\s+/);
// 定位ct-series的数组下标
const seriesIndex = classArr.indexOf('ct-series');
// 提取紧跟在ct-series之后的类名,增加边界判断避免报错
const seriesClass = seriesIndex !== -1 && classArr.length > seriesIndex + 1 ? classArr[seriesIndex + 1] : null;

多个ct-series元素场景

如果同一个图表下存在多个系列,可通过遍历批量提取:

const seriesClassList = [];
$(this).closest('.ct-chart-bar').find('.ct-series').each(function () {
  const classArr = $(this).attr('class').split(/\s+/);
  const seriesIndex = classArr.indexOf('ct-series');
  if (seriesIndex !== -1 && classArr.length > seriesIndex + 1) {
    seriesClassList.push(classArr[seriesIndex + 1]);
  }
});
// seriesClassList中存储所有ct-series后随的类名

补充说明

你使用的ChartJS本身提供了获取系列名称的原生API,不需要通过解析DOM类名的方式实现需求,直接调用对应API的性能和稳定性更高。

问题相关截图

柱状图截图1
柱状图截图2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 19:18:04