单击后显示折线图

display line chart after clicking

本文关键字:折线图 显示 单击      更新时间:2023-09-26

我使用可视化:线形图从谷歌在这个链接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>

我的问题是,当我使用这个代码总是显示在页面上我想在点击

按钮后显示折线图

我猜你想做的是这样的:

演示:

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>

我建议:

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事件处理程序(google.setOnLoadCallback(drawchart))中调用drawChart()函数,这导致它在页面加载时立即被调用,并且
  2. 你没有任何按钮点击(在你发布的HTML),或事件处理程序来处理点击该元素(如果它存在,但由于某种原因,没有显示)。