简体   繁体   中英

Can't insert an element *after* selection in d3js

It looks like d3 has no way to insert an element after a selection.

Taking a modified version of the very first tutorial as an example where the data array has a label and a value:

data = [ { label: "Ten", value: 10 }, { label: "Fifteen", value: 15 } ];
d3.select(".chart").selectAll("div").data(data)
  .enter()
    .append("div")
    .style("width", function(d) { return d.value * 10 + "px"; })
    .text(function(d) { return d.value; });

I can't find any function that would allow me to automatically insert a label with the label text after each div. The closest I can get is the following Code Pen:

http://codepen.io/anon/pen/qHIcn

But I don't want it inside the selected element, I want it after , so it should display the label outside the graph.

Update

For anyone who wants an example of the solution: http://codepen.io/anon/pen/ICkeg

You can achieve what you want by generating a hierarchy of elements. The idea is that each div / label pair would be grouped in a container element (eg another div ), which you can then append the two elements to. The code would look something like this.

var divs = d3.select(".chart").selectAll("div").data(data)
  .enter()
  .append("div");
divs.append("div")
  .style("width", function(d) { return d.value * 10 + "px"; });
divs.append("label")
  .html(function(d) { return d.value; });

You are correct that D3 provides no functions to append elements after a selection (or before a selection for that matter). That's because you are operating on selections. That is, selections and data correspond to each other and just as it doesn't make sense to have data outside other data, D3 doesn't really allow to consider elements outside a selection.

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