如何在Highcharts的饼图中动态设置标题

时间:2014-12-11 12:30:37

标签: javascript charts highcharts pie-chart

我想使用高图表插件根据饼图中的if else条件将动态传递的文本设置为标题。我尝试了事件属性以及chart.setTitle({text:mydesiredtitle}),但它并没有帮助我。

我浏览过论坛和博客,没有任何帮助。在这里,我附上了我的代码:

var textElement;
function RenderDonutChart(container,complete,incomplete,fillColor,nonfillColor) {
var dataText = true;
//complete and incomplete are integers
//container is my div to load chart.
if(!($.isNumeric(complete)))
{
    dataText = false;
    complete = 0;
    incomplete = 100;
}
var chart = new Highcharts.Chart({
    chart: {
        renderTo: container,
        type: 'pie',
        plotShadow: false,
        backgroundColor: null,
        spacing: [0, 0, 0, 0],
        margin: [0, 0, 0, 0]
    },
    plotOptions: {
        pie: {
            animation: false,
            borderWidth: 0,
            innerSize: '90%',
            dataLabels: {
                enabled: false
            }
        },
        series: {
            states: {
                hover: {
                enabled: true
                }
            }
        }
    },
    credits: {
        enabled: false
    },
    title: {
        text: ''
    },
    title: {

        text: '',
        align: 'center',
        verticalAlign: 'middle',
        y: 10,
      },

   events: {
        load: function () {
            alert("load works");
            if(!(dataText))
            {
                if(textElement != null)
                {
                    textElement.destroy();
                }
                alert("null dataText");
                textElement = '<span style="font-family:abel-Regular;font-size:16px;color:#ffffff">Not Applicable</span>';
                chart.setTitle({text: textElement});
             }
            else
            {
                if(textElement != null)
                {
                     textElement.destroy();
                }
                alert("true dataText");
                textElement = '<div style="font-family:abel-Regular;font-size:38px;color:#e57104">'
                        + complete +
                        '%</div><br><span style="font-family:abel-Regular;font-size:16px;color:#ffffff">Completed</span>';
                chart.setTitle({text: textElement});
            }
        }
    },

    tooltip: {
        enabled: false
    },
    exporting: {
        enabled: false
    },
    series: [{
        data: [complete,incomplete]
    }],
    colors: [fillColor, nonfillColor]
});
}

1 个答案:

答案 0 :(得分:1)

this关键字引用load事件中的对象本身。使用this代替chart(在加载事件被触发时尚未设置),您就可以了。

   chart: {
        events: {
            load: function () {
                var textElement = '<span style="font-family:abel-Regular;font-size:16px;color:#000">Not Applicable</span>';
                 this.setTitle({text: textElement});
            }
        }
    },

http://jsfiddle.net/7hmcw9wu/1/