如何动态传递图形类型



我正试图通过从选择列表中选择选项来动态传递图形类型。以下是我的代码:

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

然而,我无法得到图表。我正在尝试将该选项选择为直方图,我希望该图为直方图,如果我选择饼图,则该图应为具有相同值的饼图。

您在这一行有一个错误:

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

最新更新