2012-08-28 28 views
7

Tôi muốn sử dụng google api để vẽ biểu đồ trong trang web của mình. Tuy nhiên, tôi đang gặp sự cố với chức năng google.setOnLoadCallback. Đây là mã của tôi (giản thể):google.setOnLoadCallback() không hoạt động từ tệp JS riêng biệt

mưu toan 1: (Hoạt động tốt)

<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> 

mưu toan 2: (Hoạt động tốt)

<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> 

và trong styling.js tôi viết:

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

Trong trường hợp này, mọi thứ đều hoạt động tốt.

Tuy nhiên ... mưu toan 3 (KHÔNG!)

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

Và trong styling.js tôi viết:

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"); 
} 

Cái này không hoạt động. Dường như không ai gọi là helloWorld().

Tại sao?

Trả lời

1

Tôi muốn nói rằng sự kiện setOnLoadCallback không được kích hoạt, vì bạn đang xác định gọi lại khi sự kiện tải trang đã được kích hoạt.

Chỉ cần giữ google.setOnLoadCallback(helloWorld);function helloWorld() {...} bên ngoài ngữ cảnh gọi lại trang được nạp (cả hai cách này, nếu không bạn sẽ gặp sự cố ngữ cảnh).

Các vấn đề liên quan