【问题标题】:Chartjs: common clickable legend does not work after update dataChartjs:更新数据后常见的可点击图例不起作用
【发布时间】:2020-01-11 23:48:00
【问题描述】:

一页有 2 个图表和 1 个常用图例。此图例可单击以显示/隐藏图表的图形线。这是分叉的this question

我曾尝试更新代码上方的数据。这是一种未完善的方式,但我已经能够更新图表。 “图例”文本将隐藏/显示here 中的折线图。

但是更新数据后,这个切换功能就失效了。

请尝试here

  1. 点击“图例”,显示和隐藏图形线--->确定

  2. 点击“ChangeData”按钮,图形线会改变--->OK

  3. 再次点击“图例”,图线不消失-->NG

首先,它调用 DrawChart 函数,该函数为参数绘制数据。

window.onload = function () {
 DrawChart(data_A1, data_B1);
 clickableCommonLegend();
}  

DrawChart函数通过ChartJS的典型方法绘制折线图。

 function DrawChart(data_A, data_B) {
            var ctxA = document.getElementById("myChartA").getContext("2d");
            var ctxB = document.getElementById("myChartB").getContext("2d");

             myChartA = new Chart(ctxA, {
                type: 'line',
                data:{.....
                options:{....
              });
              myChartB = new Chart(ctxB, {
                type: 'line',
                data:{.....
                options:{....
              });

clickableCommonLegend() 是从this question 派生出来的。

点击按钮函数调用“changeData()”。 该函数执行销毁图表并调用“DrawChart”

function changeData() {
  myChartA.destroy();
  myChartB.destroy();
  DrawChart(data_A2, data_B2);
  myChartA.update();
  myChartB.update();

  clickableCommonLegend();
}

我猜想destroy() 在DrawChart() 中删除所有上下文并通过document.getElementById("myChartA")... 重新定义上下文。 我认为它工作正常,但结果不是。

在可点击的CommonLegend中,

var legendItems = document.querySelector('.legend').innerHTML = myChartA.generateLegend();

legendItems 是否从 chart.destroy 中删除? 但我再次调用它。

如果你让我知道出了什么问题,我就毕业了。

当前代码存在here

【问题讨论】:

    标签: javascript charts legend


    【解决方案1】:

    我找到了解决办法。

    更改changeData()函数

    function changeData() {
    
    //  ---NOT WORK---
    // myChartA.destroy();
    // myChartB.destroy();
    // DrawChart(data_A2, data_B2);
    
    // --- OK ---        
      myChartA.data.datasets[0].data = data_A2;
      myChartB.data.datasets[0].data = data_B2;
      myChartA.update();
      myChartB.update();
    
      clickableCommonLegend();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-29
      • 2018-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多