我试图通过从选择列表中选择选项来动态传递图表类型。以下是我的代码:
<html>
<head>
</head>
<body>
<select id="ChartType" name="ChartType" onchange="drawChart()">
<option value = "0">Select Chart Type
<option value="PieChart">PieChart
<option value="Histogram">Histogram
<option value="LineChart">LineChart
<option value="BarChart">BarChart
</select>
<div id="chart_div" style="border: solid 2px #000000;" ></div>
<p id="demo"></p>
<p id="demo1"></p>
<script type="text/javascript" src="https://www.google.com/jsapi"></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(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows([
['Mushrooms', 3],
['Onions', 4],
['Olives', 1],
['Zucchini', 5],
['Pepperoni', 2]
]);
var a = document.getElementById("ChartType").value;
document.getElementById("demo1").innerHTML = "You selected: " + a;
// Set chart options
var options = {
'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300
};
// Instantiate and draw our chart, passing in some options.
//passing the value which I am reading after selecting the options from the select.
var chart = new google.visualization.document.getElementById("ChartType").value(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</body>
</html>
但是我无法获得图表。我试图选择直方图选项,我希望图形为直方图,如果我选择饼图,图形应该是具有相同值的饼图。
答案 0 :(得分:1)
这一行有错误:
var chart = new google.visualization.document.getElementById("ChartType").value(document.getElementById('chart_div'));
它应该是:
var chart = new google.visualization[document.getElementById("ChartType").value](document.getElementById('chart_div'));
要将字符串用作键,您必须使用[]
。原因如下:
var a = "someProperty";
var myObject = {
someProperty: 3,
a: 4
};
console.log(myObject.a); // 4
console.log(myObject[a]); // 3
console.log(myObject.someProperty); // 3
console.log(myObject["someProperty"]); // 3