将HighCharts呈现到类而不是id?

21

我有以下代码,它运行良好:

$(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'
                    }
                });

            }
        });
    }
});

HTML大致如下:

<div id="portlet_content_18">

用户可以动态选择他想要在屏幕上显示的“portlet”。他还可以选择多次在屏幕上显示相同的“portlet”以进行比较。
因此,如果最终HTML变成:
<div id="portlet_content_18">
<div id="portlet_content_18">

只有第一个 div 中出现了图表内容,而第二个则是空白的。我该如何解决这个问题?


1
你不能有多个id,但可以尝试使用“class”。将其更改为class =“port-18”,并确保在“success”上更新它。 - Ido Green
2个回答

18

4
我尝试过了,但是运气不太好。这里是我尝试的代码jsfiddle链接:http://jsfiddle.net/Chmts/ - oshirowanen
5
仅使用$container是行不通的。正如highcharts的jsfiddle演示所示,您必须指定$container[0]。 - Jesse Schoff

15

正如Ido已经所说的,您不能有多个id,但可以有多个类。

我必须执行以下操作:

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

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

另外,你并不一定需要将Chart对象分配给一个变量 - 至少我不想这样做。

希望能对某些人有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接