Rendering HighCharts to class instead of id?

2019-02-08 00:12发布

问题:

I have the following which works fine:

$(document).ready(function() {

    get_data_for_chart();

    function get_data_for_chart() {
        $.ajax({
            url: 'get_data.aspx?rand=' + Math.random(),
            type: 'GET',
            dataType: 'json',
            error: function(xhr, status, error) {
                console.log(status);
                console.log(xhr.responseText);
            },
            success: function(results) { 
                var chart1;

                chart1 = new Highcharts.Chart( {
                    chart: {
                        renderTo: 'portlet_content_18',
                        defaultSeriesType: 'column'
                    }
                });

            }
        });
    }
});

Where the HTML looks something like this:

<div id="portlet_content_18">

The user can dynamically select which portlet s/he wants on screen. S/He can also select to have the same portlet on the screen more than once for comparison reasons.

So if the HTML ends up becoming:

<div id="portlet_content_18">
<div id="portlet_content_18">

Only the first div gets populated with the chart, and the second one remains blank. How can I get around this issue?

回答1:

Yes you can. See their example here: http://jsfiddle.net/gh/get/jquery/1.7.1/highslide-software/highcharts.com/tree/master/samples/highcharts/chart/renderto-jquery/

basically you assign an jQuery element to a variable:

renderTo: $('.myclass')[0]



回答2:

As Ido already said, you can't have multiple ids, but you can have multiple classes.

I had to do the following:

var $containers = $('.container'),
    chartConfig = {
        chart: {
            renderTo: null,
            defaultSeriesType: 'column'
        }
    };

$containers.each(function(i, e){
    chartConfig.chart.renderTo = e;
    new Highcharts.Chart(chartConfig);
});

Also, you don't really have to assign the Chart object to a variable - at least I didn't want to.

Hope it helps somebody.