如何在函数中保存全局变量值?

时间:2018-10-21 01:45:26

标签: javascript charts

我有checkValue()试图从用户那里获取输入,将其保存在全局变量中,然后将全局变量传递到drawChart()

但是似乎在drawChart()中,全局变量值仍然保持不变(等于0)

这是我的代码

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

  var i_I=0;
  var m_C=0;
  var t_A=0;

function checkValue(){

    var ii = document.projections.initial_investment.value;
    var mc = document.projections.market_contribution.value;
    var ta = document.projections.target_amount.value;

  if(ii==""){ii=0;}
  if(mc==""){mc=0;}
  if(ta==""){ta=0;}

  i_I=ii;
  m_C=mc;
  t_A=ta;  

  drawChart(i_I,m_C,t_A); 


}


      google.charts.load('current', {'packages':['line']});
      //google.charts.setOnLoadCallback(function() { drawChart(data1,data2,data3); });
      google.charts.setOnLoadCallback(drawChart);

    function drawChart(d1,d2,d3) { 

      var dTotal= d1+d2+d3;


      var data = new google.visualization.DataTable();
      data.addColumn('number', 'X');
      data.addColumn('number', 'AA');
      data.addColumn('number', 'A');
      data.addColumn('number', 'B');
      data.addColumn('number', 'C');
      data.addColumn('number', 'D');

      data.addRows([
        [2019, dTotal, dTotal, dTotal, dTotal, dTotal],
        [2020, dTotal+10, dTotal+7, dTotal+4, dTotal+2, dTotal+1],
        [2021, dTotal+19, dTotal+13, dTotal+8, dTotal+5, dTotal+2],
        [2022, dTotal+26, dTotal+18, dTotal+12, dTotal+7, dTotal+4],
        [2023, dTotal+32, dTotal+25, dTotal+16, dTotal+10, dTotal+7]
      ]);

1 个答案:

答案 0 :(得分:0)

尝试将style属性移至<td>标签,而不是<div>
然后将宽度更改为50% ...

您还可以将width: '100%'添加到图表选项...

请参阅以下工作片段...

google.charts.load('current', {'packages':['corechart','table']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Stock type');
  data.addColumn('number', 'Number of stock');
  data.addRows([
    ['Canadian',14],
    ['US', 17],
    ['International', 21],
    ['Other', 10]
  ]);

  var piechart_options = {
    title: 'Investment ratio',
    pieHole: 0.4,
    width: '100%'
  };
  var piechart = new google.visualization.PieChart(document.getElementById('piechart_div'));
  piechart.draw(data, piechart_options);

  var table_options = {
    title: 'Detail',
    width: '100%'
  };
  var tablechart = new google.visualization.Table(document.getElementById('table_div'));
  tablechart.draw(data, table_options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<table class="columns" width="100%" height="100%">
  <tr>
    <td style="border: 1px solid #ccc; width: 50%; height: 100%;"><div id="piechart_div"></div></td>
    <td style="border: 1px solid #ccc; width: 50%; height: 100%;"><div id="table_div"></div></td>
  </tr>
</table>