单击后显示折线图

时间:2014-05-18 00:52:00

标签: javascript

我正在使用此链接中的谷歌可视化:折线图 https://google-developers.appspot.com/chart/interactive/docs/gallery/linechart

这是代码

<html>
 <head>
 <script type="text/javascript" src="https://www.google.com/jsapi"></script>
 <script type="text/javascript">
  google.load("visualization", "1", {packages:["corechart"]});
  google.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = google.visualization.arrayToDataTable([
      ['Year', 'Sales', 'Expenses'],
      ['2004',  1000,      400],
      ['2005',  1170,      460],
      ['2006',  660,       1120],
      ['2007',  1030,      540]
    ]);

    var options = {
      title: 'Company Performance'
    };

    var chart = new    google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
  }
 </script>
 </head>
 <body>
 <div id="chart_div" style="width: 900px; height: 500px;"></div>
</body>
</html>

我的问题是当我使用此代码时始终显示在页面上 我想在点击按钮

后显示折线图

2 个答案:

答案 0 :(得分:0)

我想你想做的是这样的事情:

DEMO: http://jsfiddle.net/K5aMG/3/

<强> JavaScript的:

    function showChart(){
      document.getElementById('mychart').style.display='block';
    }

<强> HTML:

<div id="mychart" style="display:none;">     
   <div id="chart_div" style="width:900px; height: 500px;"></div>
</div>
<div onclick="showChart();">click here to show a chart </div>

希望这有帮助。

答案 1 :(得分:0)

我建议:

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

// bind a function to the onload event:
google.setOnLoadCallback(initialise);

function drawChart() {
    var data = google.visualization.arrayToDataTable([
        ['Year', 'Sales', 'Expenses'],
        ['2004', 1000, 400],
        ['2005', 1170, 460],
        ['2006', 660, 1120],
        ['2007', 1030, 540]
    ]);

    var options = {
        title: 'Company Performance'
    };

    var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}

// the function bound to the onload event handler:
function initialise(){
    // getting a reference to the button element (that I added,
    // which isn't in your own code):
    var button = document.getElementById('showChart');
    // using a simple event-handler to bind a function to the onclick event:
    button.onclick = function () {
        // draw the chart:
        drawChart();
        // remove the button element:
        button.parentNode.removeChild(button);
    };
}

JS Fiddle demo

以上使用以下HTML:

<button id="showChart">Show the chart</button>
<div id="chart_div" style="width: 900px; height: 500px;"></div>

您自己的图表显示为加载页面而不是单击按钮元素的原因是:

  1. 您在onload事件处理程序(drawChart())中调用了google.setOnLoadCallback(drawchart)函数,这导致在页面加载时立即调用它,并且
  2. 您没有任何按钮可以点击(在您发布的HTML中),也没有处理点击该元素的事件处理程序(如果存在,但由于某种原因,未显示)。< / LI>