将选项中的动态变量传递给Google图表

时间:2019-01-03 13:15:11

标签: javascript charts google-visualization google-chartwrapper

我正在尝试通过变量在Google图表选项中传递序列号。但是,它不接受将其作为变量,而是将其作为字符串。您可以在Image1中看到我已将Series参数SecondseriesColumnNumber作为变量传递,其值为1。

图片1 Image 1

但是在输出中,它会将其视为字符串,而不是如下所示的序列号

图片2

enter image description here

其他参数正在正确考虑值,而不是第一个。我该如何进行这项工作?我的代码在下面

var options = {
    title: title,
    width: width,
    height: height,
    bar: { groupWidth: '75%' },
    chartArea: { left: "8%", right: "8%", top: "10%", width: "100%", height: "75%" },
    backgroundColor: 'transparent',
    tooltip: { textStyle: { color: 'black' }, isHtml: true },
    isStacked: isStacked,
    seriesType: seriesType,
    series: { SecondseriesColumnNumber: { type: SecondseriesType } },
    hAxis: { slantedText: true }
};

var chart = new google.visualization.ComboChart($('DivSeries')[0]);

1 个答案:

答案 0 :(得分:2)

问题与JavaScript语法有关。
您不能在对象的定义中使用变量作为键。
您必须先创建对象,然后才能使用变量添加其他键。

定义对象后,有两种获取/设置对象键值的方法。
以下两个都将为title返回相同的值。

var title = options.title;
var title = options['title'];

在后者中,我们可以用一个变量代替标题键。

var key = 'title';
var title = options[key];

在这种情况下,根据需要定义静态选项。

var options = {
    title: title,
    width: width,
    height: height,
    bar: { groupWidth: '75%' },
    chartArea: { left: "8%", right: "8%", top: "10%", width: "100%", height: "75%" },
    backgroundColor: 'transparent',
    tooltip: { textStyle: { color: 'black' }, isHtml: true },
    isStacked: isStacked,
    seriesType: seriesType,
    series: {},
    hAxis: { slantedText: true }
};

然后您可以使用变量进一步定义系列选项。

var SecondseriesColumnNumber = 1;
options.series[SecondseriesColumnNumber] = { type: SecondseriesType };