要创建此DOM:
<g>
<rect></rect>
<circle></circle>
</g>
Run Code Online (Sandbox Code Playgroud)
从.enter()选择,我尝试:
someUpdate.enter()
.append('g')
.attr('class', 'my-group')
.append('rect')
.attr('class', 'my-rect')
// I'd like to get the .parent() here
.append('cicle')
.attr('class', 'my-circle')
Run Code Online (Sandbox Code Playgroud)
由于.append('rect')将选择更改为,因此无法使用rect。
打破这个:
const update = someUpdate.enter()
.append('g')
.attr('class', 'my-group')
update
.append('rect')
.attr('class', 'my-rect')
update
.append('cicle')
.attr('class', 'my-circle')
Run Code Online (Sandbox Code Playgroud)
作品。
但是,我想知道是否有更清洁的方法?
D3 中没有像 jQuery 那样遍历 DOM 的方法.parent()。因此,将其分解为单独的语句的方式将是正确的方法。
另一方面,按照您最初建议的方式进行操作也并非完全不可能。就在昨天,我发布了“D3.js - Selection.call() 返回什么?”的答案。解释如何准确返回所调用的选择以允许方法链接。记住这一点,你可以这样做:selection.call()
d3.select("svg").selectAll("g")
.data([1])
.enter().append('g')
.call((parent) => parent.append('rect')
.attr("fill", "red")
.attr("width", 100).attr("height", 100))
.call((parent) => parent.append('circle')
.attr("fill", "blue").attr("r", 50));Run Code Online (Sandbox Code Playgroud)
<script src="https://d3js.org/d3.v4.js"></script>
<svg></svg>Run Code Online (Sandbox Code Playgroud)
调用的两个函数.call()都将传递先前输入的<g>元素的相同选择,在本例中恰好是父元素。
尽管可以通过这种方式实现,但该解决方案有其缺点。首先,对于任何经验丰富的 D3 开发人员来说,它都会显得有些奇怪和尴尬,如果您想与其他人共享或讨论您的代码,这可能会使事情变得复杂。其次,尽管我将这个参数命名为parameter parent(在本例中就是这样),但它仍然不是真正等同于jQuery 的.parent()方法。它只会传入并返回完全相同的选择,无论是父选择还是其他选择。
| 归档时间: |
|
| 查看次数: |
814 次 |
| 最近记录: |