首页 > 解决方案 > 在初始渲染后使用jquery更新highcharts图表对象的轴(django)

问题描述

我似乎可以弄清楚一个基本问题

我的 django 应用程序中有一个 highcharts 图表,该图表正在加载到模板中。图表的数据是通过 ajax 填充的。

我想在图表上方添加一个按钮,如果单击该按钮,则会将轴切换为对数(而不是默认的线性),但我似乎无法完成这项工作

这是我的代码

HTML

<button id="target" type='button' > switch to log </button>   
<div id="container1" style="width:100%; height:400px;"></div>

Javascript

<script>

$(document).ready(function() {

     var chartOptions = {
        chart: {
            renderTo: 'container1',
            type: 'line',
        },
        title: {text: null},
        xAxis: {title: {text: null}, labels: {rotation: -45}},
        yAxis: {title: {text: 'Item counts'}, 
                type: 'linear',
                stackLabels: {enabled: true},
        },
        plotOptions: {column: {dataLabels: {enabled: false}, stacking: 'normal'}},
        series: [{}],        
    };

    var chartDataUrl = "{% url 'global_trend_chart' %}" ;  

    $.getJSON(chartDataUrl,
        function(data) {
            chartOptions.xAxis.categories = data['chart_data']['date'];
            chartOptions.series[0].name = 'Global counts';
            chartOptions.series[0].data = data['chart_data']['item_counts'];
            var chartA = new Highcharts.Chart(chartOptions);
    });

    $( "#target" ).click(function() {    
        chartA.update({
            yAxis: {
                type: 'logarithmic',
            }

        });

    });

} );

</script>

我很感激帮助

标签: jquerydjangohighcharts

解决方案


chartA点击回调函数范围内不存在Tha变量。您需要在更高级别上声明它,例如:

var chartDataUrl = "{% url 'global_trend_chart' %}";  
var chartA;

$.getJSON(chartDataUrl,
    function(data) {
        chartOptions.xAxis.categories = data['chart_data']['date'];
        chartOptions.series[0].name = 'Global counts';
        chartOptions.series[0].data = data['chart_data']['item_counts'];
        chartA = new Highcharts.Chart(chartOptions);
});

$( "#target" ).click(function() {    
    chartA.update({
        yAxis: {
            type: 'logarithmic',
        }
    });
});

现场演示:http: //jsfiddle.net/BlackLabel/6m4e8x0y/4935/


推荐阅读