一个d3.select …相当于jQuery.children()

我正在使用d3在enter()上附加一些元素,然后再更新它们。 但是,下次我尝试选择这些元素时,选择比原始元素大得多。 这是因为原始选择元素现在具有相同类型的子元素,例如: 。 我希望selectAll()只能在jQuery这样的第一个死亡级别工作。孩子们()在d3中有等价物吗? 如果不是什么最有效的方式来垫片呢?

没有与jQuery.children()相当的东西。 这通常通过为要一起选择的元素分配一个区别类来处理,例如这样的事情。

 svg.selectAll("g").data(data) .enter() .append("g") .attr("class", "parent") .append("g") .attr("class", "child"); svg.selectAll("g"); // all g elements svg.selectAll("g.parent"); // only parents svg.selectAll("g.child"); // only children 

这是一个更好的方法:

 var parent = d3.selectAll(".myParentClass"); parent.each(function(d,i) { var children = d3.selectAll(this.childNodes); console.log(children); }); 

这样,您就不需要不必要地将类添加到可能是100个(或甚至更多)子节点的类中。

您也可以使用CSS选择器选择子项。 这是我从索引中选择孩子的方法:

 d3.select(`#${parentId} > *:nth-child(${index + 1})`) 

所以我认为这是有效的:

 d3.selectAll(`#${parentId} > *`) 

在派对之后,但至少在d3版本4中, selection.selectAll()可以使用一个函数,其结果是一个数组,其中包含要根据前一个选择中的选定元素进行选择的新元素:

 var parent = d3.selectAll(".myParentClass"); var children = parent //Convert selection to selection representing the children .selectAll(function() { return this.childNodes; }) //Apply filter to children .filter('g') ; 

与之前的答案相比,这种方法的主要好处是selection.data()函数仍然可以正常工作。 先前提出的方法分配来自新的单独的d3.select()调用的结果,不允许这样做。

就像拉尔斯说的那样,在D3中没有相当于’children()’的方法,但是这里给我写的d3.selection原型留下了一点延伸。 我希望必须帮助你(这么晚)。

 d3.selection.prototype.children = function(d){ var that = this.node(); return this .selectAll(d) .filter(function(){ return that == this.parentNode; }); };