带有var视图的谷歌可视化drawTable()不起作用

Google visualization drawTable() with var view not working

本文关键字:drawTable 不起作用 可视化 谷歌 var 视图 带有      更新时间:2023-09-26

以下是我的代码:

<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load("visualization", "1", {packages:["table"]});
var table = new google.visualization.Table(document.getElementById('chart_div'));
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawTable);
var jsonData = ${requestScope.jsonData};
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var view = new google.visualization.DataView(data);
var addButton = document.getElementById('add');
var removeButton = document.getElementById('remove');
function drawTable() {
  table.draw(view);
}
removeButton.onclick=function(){
    view.hideColumns([1]);
    drawTable();
}
drawTable();
</script>
</head>

当我在drawTable()函数中包含以下行时,它是有效的,而把它们放在外面(就像上面的代码中一样)是不起作用的。

var jsonData = ${requestScope.jsonData};
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
var view = new google.visualization.DataView(data);

我想把它们放在外面的原因是,我正试图从另一个函数访问var视图,该函数将在单击按钮时隐藏视图的列。

感谢您提前提供的帮助。

google.setOnLoadCallback(drawTable);的目的是避免在加载库之前调用googleapi的函数,因为它是通过异步加载的。因此,无论何时使用api,它都应该始终位于drawTable()函数内部或该函数之后运行的其他地方。

为了能够使用drawTable()外部的数据,您只需要在外部创建var,然后在内部修改它:

var view = null;
var table = null;
function drawTable(){
    //your code... 
    var table = new google.visualization.Table(document.getElementById('chart_div'));
    //your code... 
    var view = new google.visualization.DataView(data);
    //your code... 
}

然后你可以做:

removeButton.onclick=function(){
    if(view != null && table != null){
        view.hideColumns([1]);
        table.draw(view);
    }
}