提问者:小点点

如何从动态创建的图表中获取ChartJs对象


我有一个LandingPage,它使用ChartJs动态加载图表。

我需要得到点击的图表和它的属性值。

定义图表的代码位于检索到的动态生成列(bootstrap)的循环中:

var canvasId = columnID.replace("col", "");
    canvasId = parseInt(canvasId);
    var canvasChart = $("#canvas" + canvasId).get(0).getContext("2d");

    chart = new Chart(canvasChart,
        {
            type: type,
            data: { etc etc

onClick事件调用一个模态弹出窗口并设置它的元素,但我需要得到正确的图表(每个图表都有不同的画布id)

function chart_click(colId)
{
    var parentId = $("#" + colId).closest('.colm').prop("id");
    document.getElementById('ChartEditId').value = parentId;

    // Get the chart's properties. The chart (ID) could be 'canvas01,..canvas09'
    var ChartObject =....HELP
    var type= ??;
    var legendPosition= ??;
    var data = ??.data.datasets...:
    etc..

   // Set the modal's elements from the chart properties
   ...code to set modal's elements

    // Show the ChartEdit modalPopup with it's matched elements' property values
    chartEditpopup.style.display = 'block';
}

谢谢


共1个答案

匿名用户

在制作图表时,将对象存储在一个包含2个值的数组中,包括图表对象和该图表的id。这样,当您单击图表时,您就可以从数组中选择正确的对象。

您还可以将chart.js对象存储在一个数组中,并确保该对象的索引在id中,然后解析出索引并从数组中获取该元素,而不是跟踪id的with object