Highcharts问题更新图表类型:无法识别高图功能

时间:2015-05-27 20:17:50

标签: javascript jquery charts highcharts

我正在尝试更新我当前的新图表,我有一个新的图表类型,但是我很难这样做。

我在页面中嵌入了javascript,如下所示

<script>


chart = $(function () {
    $('#chart_example').highcharts({
        chart: {
            type: 'line'
        },
        title: {
            text: 'Traffic'
        },
        xAxis: {
            categories: ['November', 'December', 'January']
        },
        yAxis: {
            title: {
                text: 'Views'
            }
        },
        series: [{
            name: 'Hello',
            data: [50, 30, 60]
        }]
    });
  });
</script>

我在页面底部有以下两个脚本

<script src="http://code.highcharts.com/highcharts.js"></script>
....
<script src="custom_script"></script>
</body>
</html>

在自定义脚本中,我想将高线图库从折线图更新为条形图。我查看了API并找到了update method 这会带来新的选择。所以我尝试了以下内容:

$(document).on('click' , '#button' , function() {
     var options = new Object();
      options.chart = new Object();
      options.chart.type = 'bar';
      options.chart.renderTo = 'container';
      chart.update(options, true);
      //the container the chart is in
      $('#chart_example').show();
...

但是我得到了

Uncaught TypeError: chart.update is not a function(anonymous function) @ custom_script=1:41m.event.dispatch @ jquery.min.js:3m.event.add.r.handle @ jquery.min.js:3

我的想法是javascript的顺序错了,但我似乎有正确的javascript。我的问题是:

1)此图表变量是否设置正确?我的理解是,一个未设置var的变量是自动全局的 2)导致此错误的原因是什么,如何修复以使其正确更新?

提前谢谢!

2 个答案:

答案 0 :(得分:2)

http://jsfiddle.net/2j1g200g/29/

var options = {
        chart: {
            type: 'line',
            renderTo: 'chart_example'
        },
        title: {
            text: 'Traffic'
        },
        xAxis: {
            categories: ['November', 'December', 'January']
        },
        yAxis: {
            title: {
                text: 'Views'
            }
        },
        series: [{
            name: 'Hello',
            data: [50, 30, 60]
        }]
    };
chart = new Highcharts.Chart(options);
options.chart.type = 'bar';
chart = new Highcharts.Chart(options);

答案 1 :(得分:1)

运行它,它应该得到你想要的。我提供了一个演示按钮。

chartOptions = {
  chart: {
    type: 'line'
  },
  title: {
    text: 'Traffic'
  },
  xAxis: {
    categories: ['November', 'December', 'January']
  },
  yAxis: {
    title: {
      text: 'Views'
    }
  },
  series: [{
    name: 'Hello',
    data: [50, 30, 60]
  }]
};

$('#chart_example').highcharts(chartOptions);


$(document).on('click' , '#button' , function() {
  chartOptions.chart.type = 'bar';    
  $('#chart_example').highcharts(chartOptions);
});
<button id="button">rechart</button>
<div id="chart_example"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>