问题
I have a question regarding google.visualization.Calendar. I have read the [https://developers.google.com/chart/interactive/docs/gallery/calendar#months][1] but still couldn't find any solutions
The below code is the code that I'm using for testing.
var dataTable=new google.visualization.DataTable();
dataTable.addColumn({type:'date', id:'Date'});
dataTable.addColumn({type:'number',id:'Events Found'});
dataTable.addRows([
[ new Date(2016, (05-1), 19), 400],
[ new Date(2016, 02, 23), 300],
[ new Date(2016, 05, 24), 300],
[ new Date(2016, 06, 23), 300]
]);
var chart=new google.visualization.Calendar(document.getElementById('calendarView'));
var options={
title: "Event Calendar",
width: 500,
height:400,
calendar: {
cellSize: 5 ,
focusedCellColor: {
stroke: 'red',
strokeOpacity: 0.8,
strokeWidth: 3
}
},
/*noDataPattern: {
backgroundColor: '#76a7fa',
color: '#a0c3ff'
},*/
calendar: {
underYearSpace: 2,
yearLabel: {
fontName: 'Times-Roman',
fontSize: 32,
color: '#e6ecff',
bold: true,
italic: true
}
}
};
chart.draw(dataTable,options);
I need to add a click event handler when user click the specific date. How to do that?
Here are the codes I tested with no results.
code :1
google.visualization.events.addListener(chart,'click',function(){
alert ('click');
});
code :2
google.visualization.events.trigger(dataTable, 'select', selectHandler);
function selectHandler() {
alert('A table row was selected');
}
Any tip to solve them would be appreciated.
回答1:
calendar events include 'select'
, but no 'click'
...
to use the 'select'
event, the listener must be added to the chart
,
before it is drawn.
see following example...
google.charts.load('current', {
callback: function () {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({type: 'date', id: 'Date'});
dataTable.addColumn({type: 'number', id: 'Events Found'});
dataTable.addRows([
[ new Date(2016, (05-1), 19), 400],
[ new Date(2016, 02, 23), 300],
[ new Date(2016, 05, 24), 300],
[ new Date(2016, 06, 23), 300]
]);
var chart = new google.visualization.Calendar(document.getElementById('calendarView'));
var options={
title: 'Event Calendar',
calendar: {
focusedCellColor: {
stroke: 'red',
strokeOpacity: 0.8,
strokeWidth: 3
},
underYearSpace: 2,
yearLabel: {
fontName: 'Times-Roman',
fontSize: 32,
color: '#e6ecff',
bold: true,
italic: true
}
},
};
google.visualization.events.addListener(chart, 'select', function () {
document.getElementById('msg_div').innerHTML = JSON.stringify(chart.getSelection());
});
chart.draw(dataTable, options);
},
packages:['calendar']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="calendarView"></div>
<div id="msg_div"></div>
来源:https://stackoverflow.com/questions/37983875/how-to-detect-click-event-on-date-cell-in-google-visualization-calendar