google.setOnLoadCallback()在单独的JS文件中不起作用

google.setOnLoadCallback() does not work from separate JS file

本文关键字:JS 文件 不起作用 单独 setOnLoadCallback google      更新时间:2023-09-26

我想在我的网站上使用谷歌api绘制图表。但是,我对google.setOnLoadCallback函数有问题。这是我的代码(简化):

尝试1:(效果良好)

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="js/styling.js"></script>
<script type="text/javascript">
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1.0', {'packages':['corechart']});
    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(helloWorld);
    function helloWorld() {
        alert("Hello World");
    }
</script>

尝试2:(效果良好)

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="js/styling.js"></script>
<script type="text/javascript">
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1.0', {'packages':['corechart']});
    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(helloWorld);
</script>

在styleing.js中,我写道:

function helloWorld() {
    alert("Hello World");
}

在这种情况下,一切都很好。

然而。。。尝试3(失败!)

<script type="text/javascript" src="js/styling.js"></script>

在styleing.js中,我写道:

 window.onload = function() {
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1.0', {'packages':['corechart']});
    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(helloWorld);
}   
function helloWorld() {
    alert("Hello World");
}

这个不起作用。似乎根本没有调用helloWorld()

为什么?

我想说setOnLoadCallback事件根本没有被触发,因为当页面加载事件已经被触发时,您定义了它的回调。

只需将google.setOnLoadCallback(helloWorld);function helloWorld() {...}保持在页面加载的回调上下文之外(两者都存在,否则会出现上下文问题)。