You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Google Charts堆叠条形图点击事件中获取键名?

Add Click Event to Get Key Name in Google Charts Stacked Bar Chart

Got it! To capture the corresponding key name (the value from the first DATA column, like PCX, PCG, etc.) when clicking on your stacked percentage bar chart, you can leverage Google Charts' built-in select event listener. Here's how to update your code:

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

function drawChart() {
  var data = google.visualization.arrayToDataTable([
    ['DATA', 'L', 'P'],
    ['PCX', 18, 21],['PCG', 131, 34],['PCO', 9, 3],['PGD', 441, 269],['PAH', 1, 1],['POD', 8, 5],['PCT', 80, 180],['PDD', 1, 7],['PZZ', 3, 8],['PKK', 461, 580],['PBI', 494, 248],['PKI', 2, 5],['PKL', 5, 1]
  ]);

  var options = { 
    isStacked: 'percent', 
    legend: { position: 'top' }, 
    chartArea: { left: 40 /* keep your existing settings here */ }
  };

  // Create the chart instance (replace with your actual container ID)
  var chart = new google.visualization.BarChart(document.getElementById('your-chart-container-id'));

  // Add click event listener to capture key names
  google.visualization.events.addListener(chart, 'select', function() {
    var selection = chart.getSelection();
    // Only proceed if an element is actually clicked
    if (selection.length > 0) {
      var rowIndex = selection[0].row;
      // Pull the key name from the first column (index 0) of the selected row
      var keyName = data.getValue(rowIndex, 0);
      // Use the key name however you need—log it, update UI, etc.
      console.log('Clicked key name:', keyName);
      // Example: Show an alert with the key name
      // alert('You clicked on: ' + keyName);
    }
  });

  // Render the chart
  chart.draw(data, options);
}

Key Breakdown:

  • Chart Instance: We explicitly create a BarChart instance (don't forget to replace 'your-chart-container-id' with the ID of the HTML element where your chart lives).
  • Select Event Handler: The google.visualization.events.addListener hooks into the chart's click/select event.
  • Retrieve Selection: chart.getSelection() returns an array of selected elements. For bar charts, each entry includes the row index of the clicked bar segment.
  • Fetch Key Name: Using data.getValue(rowIndex, 0), we grab the value from the first column of the selected row—this is your target key name.

You can tweak the code inside the event handler to use keyName for any action you need, like updating a display panel or triggering further data processing.

内容的提问来源于stack exchange,提问作者Maestro Vladimir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:17:25