无法访问Google JSAPI功能

时间:2015-07-04 23:36:02

标签: javascript jquery google-api frontend

我正在尝试将此Google图表示例代码移至

$(document).ready(function () {}); 

现在它被放置在Google JSAPI脚本之后的脚本标记中并且它可以正常工作,如下所示:

<!--Google JSAPI-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

<script type="text/javascript">

    google.load("visualization", "1", {packages: ["corechart"]});
    google.setOnLoadCallback(drawChart);
    function drawChart() {

        var data = google.visualization.arrayToDataTable([
            ['Task', 'Hours per Day'],
            ['Work', 11],
            ['Eat', 2],
            ['Commute', 2],
            ['Watch TV', 2],
            ['Sleep', 7]
        ]);

        var options = {
            title: question,
            backgroundColor: '#CFCFCF'
        };

        var chart = new google.visualization.PieChart(document.getElementById('SS_piechart'));

        chart.draw(data, options);
    }

</script> 

这是在我的page_tail中,就在关闭body标签之前。但是只要我把代码放在

$(document).ready(function () {});

我得到了

  

未捕获的TypeError:google.visualization.arrayToDataTable不是函数

<!--Google JSAPI-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

<script type="text/javascript">

$(document).ready(function () {

    google.load("visualization", "1", {packages: ["corechart"]});
    google.setOnLoadCallback(drawChart);
    function drawChart() {

        var data = google.visualization.arrayToDataTable([
            ['Task', 'Hours per Day'],
            ['Work', 11],
            ['Eat', 2],
            ['Commute', 2],
            ['Watch TV', 2],
            ['Sleep', 7]
        ]);

        var options = {
            title: question,
            backgroundColor: '#CFCFCF'
        };

        var chart = new google.visualization.PieChart(document.getElementById('SS_piechart'));

        chart.draw(data, options);
    }

});

</script>

我在$(document).ready函数中有一些其他代码,是否可能存在代码冲突,或者是否存在我遗漏的明显问题?

1 个答案:

答案 0 :(得分:0)

可以移动回调

google.setOnLoadCallback(drawChart);

$(document).ready(function () { 
    drawChart();
});

或JS原生

document.addEventListener("DOMContentLoaded", drawChart);