基于点击的动态高图系列

时间:2018-05-30 16:11:12

标签: jquery highcharts

是否可以使高图显示动态数据库点击按钮?

我有一个资产数组

var assets = [{
    name: "food",
    type: [{
        name: "a",
        y: 129.2
    }, {
        name: "b",
        y: 132
    }]
}, {
    name: "drink",
    type: [{
        name: "drink1",
        y: 512,
    }, {
        name: "drink2",
        y: 412,
    }]
}];

我为highcharts设置了一个空数组,用作系列

var data =[];

然后我设置标题按钮,如每个类别的名称

<button title="food">show food</button>
<button title="drink">show drink</button>

codepen

这是我第一次尝试显示动态数据,谢谢。

1 个答案:

答案 0 :(得分:1)

  

是否可以使高图显示动态数据库点击按钮?

是的,你可以做,在设置实际数据之前,你需要先串联设置第一个空白数据,然后设置实际数据。

<强>样本

&#13;
&#13;
var assets = [{
        name: "food",
        type: [{
            name: "a",
            y: 129.2
        }, {
            name: "b",
            y: 132
        }]
    }, {
        name: "drink",
        type: [{
            name: "drink1",
            y: 512,
        }, {
            name: "drink2",
            y: 412,
        }]
    }],
    colors = ['#76daff', '#b9f', '#99ffa6', '#ffc312'];


$('button').on('click', function() {
    var attr = $(this).attr('title'),
        obj = assets.find(({name}) => name === attr);
        
    chart.series[0].setData([], true);
    chart.series[0].setData(obj.type || [], true);
});

var chart = Highcharts.chart('highchart', {
    chart: {
        type: 'bar',
        backgroundColor: null,
        height: 270,
    },
    title: {
        text: ''
    },
    xAxis: {
        type: 'category',
        labels: {
            useHTML: true,
            formatter: function() {
                return '<div class="myToolTip" style="color:' + colors[this.pos % colors.length] + '">' + this.value + '</div>';
            }
        }
    },
    colors: colors,
    yAxis: {
        min: 0,
        gridLineWidth: 0,
        title: {
            text: ''
        },
        gridLineWidth: 0,
        labels: {
            enabled: false
        }
    },
    credits: {
        enabled: false
    },
    legend: {
        enabled: false
    },
    plotOptions: {
        series: {
            dataLabels: {
                enabled: true,
                crop: false,
                overflow: 'none',
                format: '<span style="color:{point.color}">{y}</span>'
            },
            colorByPoint: true
        }
    },
    tooltip: {},
    series: [{}]
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<div id="highchart"></div>

<button title="food">show food</button>
<button title="drink">show drink</button>
&#13;
&#13;
&#13;