首页 > 解决方案 > 使用函数删除c3中的图形

问题描述

在以下函数中创建图表时,如何处理图表#.destroy():

function create(i){
    chart = 'chart' + i
    chart = c3.generate(...)
}
create(1)
create(2)
create(3)

以便它创建chart1、chart2、chart3。

我试图让一个按钮调用一个函数:clear_chart:

function clear_chart(){
    for(i=1; i<4; i++){
       chart = 'chart' +i
       chart.destroy()
    }
}

我收到一个错误:未捕获的类型错误:无法读取未定义的属性“销毁”

标签: javascriptc3.js

解决方案


This happens because you're not selecting a chart doing this:

chart = 'chart' +i

You can also remove the same line from the create method as is not doing anything on your code. You're assigning a value to the chart var and then reassigning it when generating the chart the name of the var is still "chart".

The easiest way of working with chart objects is storing them in an array and using them afterwards:

var charts = [];
function create(){
    var chart = c3.generate(...);
    charts.push(chart);
}
//call create function...

function clear_chart(){
    for(i = 1; i < 4; i++){
        var chart = charts[i - 1]; 
        chart.destroy();     
    }
}

If you want to select just a specific one through their name, I suggest taking a look at jQuery selectors (if possible to add jQuery to your project) or d3 select functions.


推荐阅读