问题
Can we draw a google chart in a pop up fancybox?
I have data shown in a table, and there is a button in each row for showing google chart of each record.
Currently, my chart is always shown in the bottom after the table, but when the record is scroll over the screen, user need scroll to bottom to get the chart view. Is it possible to use fancybox or some way solving this inconvenient?
Thanks for any advise!
html:
<table>
<tr>
<td> data </td>
...
<td>
<button onclick="showChartByEmpId()"> pie chart </button>
</td>
</tr>
</table>
<div class="secondary"> </div> <!-- showing chart here -->
js:
function drawPieChart(dataArr, elementId) {
//dataArr : the data to display
//elementId : <div> element where to display chart
var data = google.visualization.arrayToDataTable(dataArr);
var chart = new google.visualization.PieChart(document.getElementById(elementId));
chart.draw(data, options);
}
function showChart(){
//alert("readyState=" + xhr2.readyState);
if(xhr2.readyState == 4) {
if(xhr2.status == 200){
var allEmp = xhr2.responseText;
var empList = JSON.parse(allEmp);
... prepare pieChartDate[] to draw chart ...
//create <div> to displaying chart in it
$('.secondary').html('<div id="chart_div" height="450" width="450"></div>');
drawPieChart(pieChartData[0], "chart_div");
...
}
function showChartByEmpId(){
var url = '/CMP/employee/emp.do';
//create XMLHttpRequest
xhr = createXHR();
if( xhr == null ){
alert("no xhr creted");
return;
}
var requestData = "action=getOneEmpJSON&empId1=" + escape(empId1) + "&empId2=" + escape(empId2);
xhr.open('POST', url, true);
xhr.onreadystatechange = showChart;
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(requestData);
}
回答1:
What I would do :
1). hide the .secondary
div
<div class="secondary" style="display:none"></div>
2). assign a class selector to each button like
<button class="doPiechart">pie chart</button>
3). bind a click
event to each
button and then show the contents of #chart_div
in fancybox after is created.
jQuery(function ($) {
$(".doPiechart").each(function (i) {
$(this).on("click", function () {
showChartByEmpId(i);
$.fancybox("#chart_div");
}); // on click
}); // each
});
Notice that you may need to tweak your showChartByEmpId()
function to pass the index of the .each()
method and eventually to include a callback to show fancybox after is completed.
See a simulated behavior in JSFIDDLE using fancybox v2.x
NOTE: .on()
requires jQuery v1.7+
来源:https://stackoverflow.com/questions/18579054/how-to-launch-fancybox-from-button-onclick-event-to-draw-google-chart