将HighCharts渲染为类而不是id?

osh*_*nen 19 javascript jquery jquery-selectors highcharts

我有以下工作正常:

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

            }
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

HTML看起来像这样:

<div id="portlet_content_18">
Run Code Online (Sandbox Code Playgroud)

用户可以portlet在屏幕上动态选择他/她想要的内容.portlet出于比较原因,他/她也可以选择在屏幕上多次使用相同的内容.

因此,如果HTML最终成为:

<div id="portlet_content_18">
<div id="portlet_content_18">
Run Code Online (Sandbox Code Playgroud)

只有第一个div填充图表,第二个保持空白.我该如何解决这个问题?

Moi*_*man 18

是的你可以.在这里查看他们的例子:http://jsfiddle.net/gh/get/jquery/1.7.1/highslide-software/highcharts.com/tree/master/samples/highcharts/chart/renderto-jquery/

基本上你将jQuery元素分配给变量:

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

  • 仅使用$ container将无法正常工作.正如来自highcharts的jsfiddle演示的那样,你必须指定$ container [0]. (5认同)
  • 我试过了,但我运气不好.这是我尝试过的一个小问题:http://jsfiddle.net/Chmts/ (4认同)

Sez*_*eza 11

正如Ido已经说过的那样,你不能拥有多个id,但是你可以拥有多个类.

我必须做以下事情:

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

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

此外,您不必将Chart对象分配给变量 - 至少我不想这样做.

希望它对某人有帮助.