如何将动态HTML表格元素按指定顺序转为数组并渲染折线图
动态表格适配Chart.js折线图实现方案
核心逻辑调整
原有代码全局查询所有单元格导致行列数据错位,改为按行遍历表格提取数据,自动适配动态增删的行列结构,实现每个x轴标签对应该行所有y轴数值,自动生成对应数量的折线系列。
修改后的表格取值函数
function getTableData(){ const rows = document.querySelectorAll('#my-table tr') const xs = [] // x轴标签数组 // 初始化y系列二维数组,子数组数量等于y列数 const yColumnCount = rows[0].querySelectorAll('.ycell').length const yDatasets = Array.from({length: yColumnCount}, () => []) rows.forEach(row => { // 提取当前行x值 const xCell = row.querySelector('.xcell') const xVal = parseFloat(xCell.textContent) xs.push(isNaN(xVal) ? 0 : xVal) // 提取当前行所有y值,分别存入对应系列数组 const yCells = row.querySelectorAll('.ycell') yCells.forEach((cell, colIndex) => { const yVal = parseFloat(cell.textContent) yDatasets[colIndex].push(isNaN(yVal) ? 0 : yVal) }) }) return {xs, yDatasets} }
修改后的图表生成函数
function chartIt(){ const data = getTableData() const ctx = document.getElementById('myChart').getContext('2d') // 销毁已存在的图表实例 const chartStatus = Chart.getChart("myChart") if (chartStatus) chartStatus.destroy() // 预设颜色池,支持多系列循环取色 const colorPool = [ { bg: 'rgba(255, 99, 132, 0.2)', border: 'rgba(255, 99, 132, 1)' }, { bg: 'rgba(54, 162, 235, 0.2)', border: 'rgba(54, 162, 235, 1)' }, { bg: 'rgba(255, 206, 86, 0.2)', border: 'rgba(255, 206, 86, 1)' }, { bg: 'rgba(75, 192, 192, 0.2)', border: 'rgba(75, 192, 192, 1)' }, { bg: 'rgba(153, 102, 255, 0.2)', border: 'rgba(153, 102, 255, 1)' }, { bg: 'rgba(255, 159, 64, 0.2)', border: 'rgba(255, 159, 64, 1)' } ] // 动态生成数据集 const datasets = data.yDatasets.map((yData, index) => { const color = colorPool[index % colorPool.length] return { label: `系列${index + 1}`, data: yData, fill: false, backgroundColor: color.bg, borderColor: color.border, borderWidth: 1 } }) new Chart(ctx, { type: 'line', data: { labels: data.xs, datasets: datasets }, options: { scales: { y: { beginAtZero: true } } } }) }
注意事项
动态增删行列时,新增的单元格需要正确添加xcell/ycell类名和contenteditable="true"属性,保证取值逻辑正常识别。
内容的提问来源于stack exchange,提问作者Vitaliy Povestev
相关产品推荐
相关产品推荐

