我目前正在网站上使用NVD3来绘制图表,其中一个页面有6个图表.我目前只为六个图表添加了6个函数,但我觉得这不是解决问题的最优雅方式.以下是相关html/javascript代码的示例:
nv.addGraph(function() { var chicago = nv.models.lineChart() .margin({top: 30, right: 60, bottom: 50, left: 80}) .x(function(d,i) { return i }) .color(d3.scale.category10().range()); chicago.transitionDuration(500); chicago.xAxis.tickFormat(function(d) { var dx = testdata[0].values[d] && testdata[0].values[d].x || 0; if (dx > 0) { return d3.time.format('%x')(new Date(dx)) } return null; }); chicago.yAxis .axisLabel('Price ($/Dth)') .tickFormat(function(d) { return '$' + d3.format(',.2f')(d) }); nv.log(testdata); d3.select('#chicago svg') .datum(testdata) .call(chicago); nv.utils.windowResize(chicago.update); return chicago; });
我如何包装该函数,以便我可以多次重复使用它而不必重复它并替换每个图形的名称(在本例中为"芝加哥")?
它很简单,这是一种方法.
HTML:
<div id='chart1'> <h3>My Chart 1</h3> <svg></svg> </div> <div id='chart2'> <h3>My Chart 2</h3> <svg></svg> </div> <div id='chart3'> <h3>My Chart 3</h3> <svg></svg> </div>
JavaScript:
// Call my charts , pass in my div id here drawChart('chart1'); drawChart('chart2'); drawChart('chart3'); //Donut chart example function drawChart(div) { var width = height = 400; nv.addGraph(function () { var chart = nv.models.pieChart() .x(function (d) { return d.label }).y(function (d) { return d.value }).width(width) .height(height) .showLabels(true) .labelThreshold(.05) .labelType("percent") .donut(true); d3.select("#" + div + " svg") .datum(exampleData()) .attr('width', width).attr('height', height) .transition().duration(350) .call(chart); return chart; }); }
这是它的工作版本.
希望能帮助到你.