3

我正在尝试在我正在呈现的图表上添加点击事件。从 chart.click 到 chart.on('click', function (e){ })。

我想要做的是允许用户选择图表上的点,对我来说现在用户做了什么选择。使用 chartist.js 有可能吗?

我通读了文档:CHARTIST.JS

我的代码:

if (item.GraphType.Description == "Line") {
    var chart = new Chartist.Line(
        container[0],
        {
            labels: d.Labels,
            series: d.SeriesData
        },
        {
            axisY: {
                offset: 60
            }
        }
    );
    chart.click(function (e) {
        console.log(e);
    });
}
4

1 回答 1

6

完全有可能,是的。Chartist 将 SVG 节点呈现到页面,因此使用 jQuery 之类的库,您可以轻松找到所需的所有节点并将事件附加到它们。您可以在要查找的节点中尽可能具体或广泛,仅将事件附加到图表上非常具体的节点或元素。

为了完整起见,这里有一个简短的示例,说明如何使用 jQuery 将单击时记录数据点值的事件附加到控制台:

$('.ct-chart-line .ct-point').click(function () {
    var val = $(this).attr("ct:value");
    console.log(val);
});

但是,如果要确保数据点在页面上,则应确保仅在创建或绘制图表时附加事件,这可以由“创建”或“绘制”事件触发:

var chart = new Chartist.Line(...);
// attach an event handler to the "created" event of the chart:
chart.on("created", function () {
    // attach the necessary events to the nodes:
    $('.ct-chart-line .ct-point').click(function () {
        var val = $(this).attr("ct:value");
        console.log(val);
    });
});
于 2016-11-29T13:07:52.817 回答