简体   繁体   English

d3.js v4 - 嵌套选择

[英]d3.js v4 - Nested Selections

In d3.js v4, nested selections don't appear to be working as they had in the past. 在d3.js v4中,嵌套选择似乎不像过去那样有效。

This works (in v3): 这工作(在第3节):

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/ https://jsfiddle.net/nwozjscs/

But not in v4: https://jsfiddle.net/nwozjscs/1/ 但不是在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. 我的感觉是这与合并(...)更改有关,但我无法找到在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. 我觉得我太习惯了v3的魔力来看明显的。

Please comment if there is a better way to do this! 请评论是否有更好的方法来做到这一点!

https://jsfiddle.net/nwozjscs/2/ 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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