使用 d3js,在我的树布局中,我需要更改所选节点 (choix1( 及其所有后代的一些属性,所以我想为所有后代提供一个类 (choix2(
.on("click", function() {
d3.select(this).classed("choix1", true); // selecting a node
d3.select(".choix1").children.classed("choix2", true); // giving a class (choix2) for all descendants
})
对于选定的节点没问题, 我希望对后代属性进行修改,但实际属性是旧属性(没有修改(。
您正在将 D3 API 与 DOM API 方法混合在一起,这显然是行不通的。尝试访问d3.select(".choix1")
返回的 D3 选择上的.children
属性会中断,因为该属性是接口ParentNode
的一部分,该接口由 DOM 的Element
接口实现,该接口是实际元素的父接口。
如果要使用.classed()
方法在子元素上设置类,则必须通过首先调用.selectAll(this.children)
将它们包装到 D3 选择中。因此,您的代码将变为:
.on("click", function() {
d3.select(this).classed("choix1", true);
d3.selectAll(this.children) // wrap the children in a D3 selection first...
.classed("choix2", true); // then call methods on that selection.
})