简体   繁体   中英

d3.js v4 - Nested Selections

In d3.js v4, nested selections don't appear to be working as they had in the past.

This works (in v3):

var data = [["1-a", "1-b"], ["2-a", "2-b"]];

var tbody = d3.select("tbody");

var row = tbody.selectAll("tr").data(data);
row.exit().remove();
row.enter().append("tr");

var cell = row.selectAll("td").data(function(d){ return d;});
cell.exit().remove();
cell.enter().append("td");
cell.text(function(d){ return d; });

https://jsfiddle.net/nwozjscs/

But not in v4: https://jsfiddle.net/nwozjscs/1/

My sense is that this has something to do with the merge(...) changes, but I haven't been able to find an example of the proper way to write a nested selection in v4.

I think I figured it out. It appears to work correctly if you merge the enter and update selections into a single selection before joining the next layer of data. This way any new data as well as any existing data at the top level will be correctly taken into account at the next level down.

This makes total sense if you think about it. I think I was just too used to the magic of v3 to see the obvious.

Please comment if there is a better way to do this!

https://jsfiddle.net/nwozjscs/2/

function render(data){
  var tbody = d3.select("tbody");

  var row = tbody.selectAll("tr").data(data);
  var rowenter = row.enter().append("tr");

  var cell = row.merge(rowenter)
    .selectAll("td").data(function(d){ return d;});

  cell.enter().append("td").text(function(d){ return d; });
}

render([["1-a", "1-b"], ["2-a", "2-b"]]);

setTimeout(function(){
    render([["1-a", "1-b", "1-c"], ["2-a", "2-b", "2-c"], ["3-a", "3-b", "3-c"]]);
}, 2000);

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