无法为Google Visualization插入Javascript select onchange功能

时间:2013-09-11 22:47:25

标签: javascript select google-visualization onchange

我是JS编程的新手。我想做一个选择选项,我可以在其中更改图表类型,例如从一行到另一行。数据源来自Google Spreadsheet。 JS代码如下:

<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>
  Select Chart Type
</title>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages:  ['linechart',corechart','barchart', 'columnchart']});
</script>
<script type="text/javascript">
var graphview;

function init() {
graphview = new google.visualization.ChartWrapper({
dataSourceUrl: 'https://docs.google.com/spreadsheet/tq?tq=select%20A,B......etc
containerId: 'visualization1', chartType: 'LineChart'


graphview.draw();
}   


google.setOnLoadCallback(init);
}
</script>
</head>
<body> 
<div id="panelgraph", width="600", height="200">
</body>
</html>

选项如下:

<select id="graphbox" name="graphbox"  onChange="getChart()">
<option value="Line">Line Chart </option>
<option value="Bar">Bar Chart</option>
<option value="Core">Area Chart</option>
<option value="Column">Column Chart</option>                                                                    
</select>

我尝试创建一个函数,但不确定如何以及在何处插入它们:

var mygraphbox = document.getElementById("graphbox"); 
var myinsertgraphhere = document.getElementById("panelgraph");      
mygraphbox.onchange =function() 

我按照一些如何进行onchange选择选项功能的例子。但是当我想将它应用于我的情况时(例如使用if-else和绘制地图)我遇到了麻烦。请帮助我如何制定它以及如何将其插入JS块。

提前谢谢你, 典

1 个答案:

答案 0 :(得分:2)

这是一个快速的解决方案;将您的JavaScript更改为:

function init () {
    var graphview = new google.visualization.ChartWrapper({
        chartType: 'LineChart',
        containerId: 'visualization1',
        dataSourceUrl: 'https://docs.google.com/spreadsheet/tq?key=<key>&gid=0',
        options: {
            // chart options
        },
        query: 'select a, b, c'
    });

    graphview.draw();

    function changeHandler () {
        graphview.setChartType(this.options[this.selectedIndex].value);
        graphview.draw();
    }

    var mygraphbox = document.querySelector("#graphbox");
    if (typeof(window.addEventListener) == 'function') {
        mygraphbox.addEventListener('change', changeHandler, false);
    }
    else if (typeof(window.attachEvent) == 'function') {
        mygraphbox.attachEvent('onchange', changeHandler);
    }
}

google.load('visualization', '1', {packages:  ['corechart'], callback: init});

并更改选择框,如下所示:

<select id="graphbox">
    <option value="LineChart">Line Chart </option>
    <option value="BarChart">Bar Chart</option>
    <option value="AreaChart">Area Chart</option>
    <option value="ColumnChart">Column Chart</option>                                                                    
</select>

使用此功能,您可以更改图表类型,而无需重新提交查询。