gpt4 book ai didi

javascript - 向对象添加 Google Chart 功能

转载 作者:行者123 更新时间:2023-11-30 16:51:56 24 4
gpt4 key购买 nike

我正在尝试向对象添加 Google 图表功能。我已经在 NetBeans 中测试了以下代码,它可以为它提供任意数据数组:

google.setOnLoadCallback(costChart);
function costChart() {
var energyType = 'Monthly Cost';
var energySavings = [1,2,3,4,5,6,7,8,9,10,11,12]; //=this.costSavings
var month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('number', energyType + ' Saved');


data.addRows([
[month[0], energySavings[0]],
[month[1], energySavings[1]],
[month[2], energySavings[2]],
[month[3], energySavings[3]],
[month[4], energySavings[4]],
[month[5], energySavings[5]],
[month[6], energySavings[6]],
[month[7], energySavings[7]],
[month[8], energySavings[8]],
[month[9], energySavings[9]],
[month[10], energySavings[10]],
[month[11], energySavings[11]]
]);

// Set chart options
var options = {'title': 'Cost Savings',
'width':400,
'height':300,
'hAxis':{format: 'currency'}
};

// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.BarChart(document.getElementById('cost_chart_div'));
chart.draw(data, options);
}

但是,我想把它放在一个对象中作为要使用的方法,类似于this.costChart()。它将访问对象内的数据,而不是任意数据,就像代码第三行中注释掉的 this.costSavings 一样。

当我将其设置为对象方法时,出现错误:“Uncaught ReferenceError: google is not defined”

关于如何正确设置此方法的任何想法?

跟进:我添加了代码行:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
function run(){
costChart();

}

但我仍然收到相同的“google not defined”错误。我已经尝试将脚本添加到该部分,但仍然不行。我尝试通过将对象作为 arg 传递给它来单独调用该函数,但仍然出现相同的错误。我觉得这可能是由于我应该包括的方式:

  google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(costChart);

但我不太确定在哪里/如何将它们包含在函数中。它们会出现在脚本的顶部,还是在调用 costChart() 的函数内,还是在 costChart() 函数本身内,等等...?

最佳答案

您收到“google is not defined”,因为您需要在代码顶部使用它:

  <div id="cost_chart_div"> </div> 

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});

一旦准备就绪,您就可以轻松地使用 this.costSavings 进行操作。

关于javascript - 向对象添加 Google Chart 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30401022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com