Third variable in D3 anonymous function

后端 未结 2 1408
名媛妹妹
名媛妹妹 2020-12-10 13:38

Let\'s say you\'ve got a selection with some data bound to it and you use the typical inline anonymous function to access that data:

 d3.select(\"#whatever\"         


        
2条回答
  •  失恋的感觉
    2020-12-10 14:24

    A note on Lars's reply, which is correct but I found one more feature that is helpful.

    The j element gives the index of the element without regard to the nesting of the parent elements. In other words, if you are appending and logging as follows, the final circles are treated as a flat array, not as a group of nested arrays. So your indexes will be scaled from 0 to the number of circle elements you have, without regard to the data structure of your nesting.

    var categorygroups = chart.selectAll('g.categorygroups')
          .data(data)
          .enter()
            .append('g').attr('class','categorygroups');
    
          var valuesgroups = categorygroups.selectAll('g.valuesgroups')
            .data(function(d) {return d.values; }).enter().append('g').attr('class','valuesgroups');
    
            valuesgroups.append('text').text(function(d) {
              return d.category
            }).attr('y',function(d,i) { return (i + 1) * 100 }).attr('x',0);
    
          var circlesgroups = valuesgroups.selectAll('g.circlesgroups')
            .data(function(d) {return d.values; }).enter().append('g').attr('class','circlesgroups');
    
            circlesgroups.append('circle').style('fill','#666')
            .attr('cy',function(d,i,j) { console.log(j); return (j + 1) * 100 })
            .attr('cx',function(d,i) { return (i + 1) * 40 });
    

提交回复
热议问题