简体   繁体   中英

D3JS nested insert. Example with SVG: text into group

I have been checking some tutorials about D3JS about joining and nesting, but I can not solve the next problem, I was also checking example like http://bl.ocks.org/4061961 but I don't find the solution between all the magic.

So, I have an array of elements, with this array I can create a "g" label for each element, and I can create a "text" label for each element, but I can not manage to put the "text" label inside the "g" label.

So what a I get in the DOM is this: HTML -> BODY -> SVG -> G HTML -> BODY -> SVG -> TEXT

And what I'll like is this: HTML -> BODY -> SVG -> G -> TEXT

My small testing code is this one:

data = ["1", "2", "3", "4", "5"];

// Grups de selecció
svg.selectAll("svg_group")
  .data(data)
  .enter()
  .append("g")
  .attr("class", 'svg_group');

// Text dels dies / anys
svg.selectAll("g .svg_group")
  .data(data)
  .enter()
  .append("text")
  .text( function(d) { return d; } );

I'll appreciate any help. Thanks in advance.

Update 16:08

I need to add more than one element to the group and if possible in two steps. Now I have this in the DOM:

  <svg id="gantt" width="500" height="500">
    <g class="svg_group">
    <g class="svg_group">
    <g class="svg_group">
    <g class="svg_group">
    <g class="svg_group">
    <text>1</text>
    <text>2</text>
    <text>3</text>
    <text>4</text>
    <text>5</text>
    <line>1</line>
    <line>2</line>
    <line>3</line>
    <line>4</line>
    <line>5</line>  
  </svg>

And I like something like this:

  <svg id="gantt" width="500" height="500">
    <g class="svg_group">
      <text>1</text>
      <line>1</line>
    </g>
    <g class="svg_group">
      <text>2</text>
      <line>2</line>
    </g>
    <g class="svg_group">
      <text>3</text>
      <line>3</line>
    </g>
    <g class="svg_group">
      <text>4</text>
      <line>4</line>
    </g>
    <g class="svg_group">
      <text>5</text>
      <line>5</line>
    </g>
  </svg>

Example in: http://jsfiddle.net/y394h/10/

How about this?

svg.selectAll("svg_group")
  .data(data)
  .enter()
  .append("g")
  .attr("class", 'svg_group')
  .append("text")
  .text( function(d) { return d; } );

or

var group = svg.selectAll("svg_group")
  .data(data)
  .enter()
  .append("g")
  .attr("class", 'svg_group');

group.append("text")
  .text( function(d) { return d; } );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM