2013-04-17 41 views
0

我在下面的代码中使用Google的图表库。目前,我有一个selectHandler函数返回列行的警报。如何使用Google可视化实现自定义事件?

而不是列号的警报,我试图实现一些JavaScript,发送下面显示的项目'钥匙'的警报。我如何得到这个?

  <% @frequency.each do |key,value| %> 
       ['<%= key %>', <%= value %>], 
       <% end %>  

的Javascript

<script type="text/javascript"> 
    google.load("visualization", "1", {packages:["corechart"]}); 
    google.setOnLoadCallback(drawChart); 

    function drawChart() { 

     // OPTIONS 
     var options = { 
     title: 'Most common phrases in pro-Microsoft Reviews (<%= @reviews.count %> reviews analyzed)', 
     vAxis: {title: 'Phrases', titleTextStyle: {color: 'red'}}, 
     tooltip: {isHtml: true}, 
     animation:{ 
      duration: 2000, 
      easing: 'out', 
     } 
     }; 

     // DATA 
     var data = google.visualization.arrayToDataTable([ 
     ['Phrase', 'Frequency'], 
      <% @frequency.each do |key,value| %> 
       ['<%= key %>', <%= value %>], 
       <% end %> 
     ]); 

     // CHART DRAWING 
     var chart = new google.visualization.BarChart(document.getElementById('chart_div')); 
     chart.draw(data, options); 
     google.load("visualization", "1", {packages:["corechart"]}); 
     google.setOnLoadCallback(drawChart); 

     //setup listener 
     google.visualization.events.addListener(chart, 'select', selectHandler); 

     // The select handler. Call the chart's getSelection() method 
     function selectHandler() { 
      var selection = chart.getSelection(); 
      alert('That\'s column no. '+selection[0].row); 
     } 



    } 


</script> 

回答

1

下面是一个简单的例子,显示了如何获取与使用data.getValue()自定义处理程序列0(“键”所选项目),该行的价值:

function drawVisualization() { 
    // Create and populate the data table. 
    var data = new google.visualization.DataTable(); 
    data.addColumn('string', 'Department'); 
    data.addColumn('number', 'Revenues Change'); 
    data.addRows([ 
    ['Computer', {v: 12, f: '12.0%'}], 
    ['Sports', {v: -7.3, f: '-7.3%'}], 
    ['Toys', {v: 0, f: '0%'}], 
    ['Electronics', {v: -2.1, f: '-2.1%'}], 
    ['Food', {v: 22, f: '22.0%'}] 
    ]); 

    // Create and draw the visualization. 
    var table = new google.visualization.Table(document.getElementById('visualization')); 

    var formatter = new google.visualization.TableArrowFormat(); 
    formatter.format(data, 1); // Apply formatter to second column 

    table.draw(data, {allowHtml: true, showRowNumber: true}); 

    //setup listener 
    google.visualization.events.addListener(table, 'select', selectHandler); 

    // The select handler. Call the chart's getSelection() method 
    function selectHandler() { 
    var selection = table.getSelection(); 
    alert('That\'s row '+ data.getValue(selection[0].row, 0)); 
    } 

} 

你应该能够做到为自己的代码相同的只是通过改变该行:

alert('That\'s column no. '+selection[0].row); 

要这样:

alert('That\'s row '+ data.getValue(selection[0].row, 0)); 
相关问题