2013-09-23 97 views
0

我试图使用nvd3和d3生成多个图表。我有适量的div。添加多个图表d3,nvd3使用for循环

如果我删除了forloop,那么我得到一个图表#chart1。如果我把for循环,然后我得到一个图表只在#chart2

任何人都可以看到为什么?

for (var j = 1; j <= 2; j += 1) { 
    var s = '#chart' + j.toString() + ' svg'; 
    console.log(s); 

    nv.addGraph(function() { 
     var chart = nv.models.lineChart(); 

     chart.xAxis.axisLabel('Time step').tickFormat(d3.format(',r')); 
     chart.yAxis.axisLabel('eig(' + j.toString() + ')').tickFormat(d3.format('.02f')); 
     d3.select(s).datum(function() { 

      var sin = [], cos = []; 
      for (var i = 0; i < 100; i++) { 
       sin.push({ 
        x : i, 
        y : Math.sin(i/10) 
       }); 
       cos.push({ 
        x : i, 
        y : .5 * Math.cos(i/10) 
       }); 
      } 

      result = []; 
      result.push({ 
       values : sin, 
       key : 'sin', 

      }); 

      return result; 
     }).transition().duration(500).call(chart); 

     nv.utils.windowResize(chart.update); 
     return chart; 
    }); 
} 

回答

2

首先,它不是普通就像你有(数据驱动文件)使用一个for循环。在D3最好是选择你想要的所有元素,并使用.each()像这样

d3.selectAll('.chart svg') 
    .each(function(data){ 
     // Do what you would have done in the loop here 
}) 

其次,它看起来像有使用匿名函数你的方式(不知道的问题,为什么不花太多时间看)。通过将其称为实际功能,它可以工作。

nv.addGraph(addMyChart(this)) 

看到这个的jsfiddle http://jsfiddle.net/a5BYP/