我完全承认我才接触 D3 几周,但我已经在这里坐了几个小时,现在调试无济于事。
注意隐藏在匿名函数中的两个 console.log(d)
语句。 'dummy' 属性中的返回值,d
属性中的不返回值。
这两者有什么不同?
var myEdges = [
{
in: "934e3e11-3f9b-11e9-b2b9-c54f58764873",
out: "936807a1-3f9b-11e9-b2b9-c54f58764873"
},
]
svg.selectAll('path:not([elementType=temp-path])').data(myEdges)
.enter().append('path')
.attr("fill", "none")
.attr("stroke", "blue")
.style("stroke-width", "2px")
.attr('dummy', function(d) { console.log(d); return d;})
.attr('d', d3.linkVertical()
.x(function(d) { console.log(d); return d.in; })
.y(function(d) { return d.out; }));
最佳答案
问题不在于数据 (d
) 属性没有被传递:它是。这里的问题只是链接生成器期望的数据结构。
如果您查看 API ,您会看到链接生成器默认情况下需要这样的数据结构:
{
source: foo,
target: baz
}
顺便说一句,您可以使用 link.source()
和 link.target()
更改这些属性。
因此,如果我们更改您的数据结构,控制台将正常工作:
var svg = d3.select("svg");
var myEdges = [{
source: { in: "934e3e11-3f9b-11e9-b2b9-c54f58764873",
out: "936807a1-3f9b-11e9-b2b9-c54f58764873"
},
target: { in: "934e3e11-3f9b-11e9-b2b9-c54f58764873",
out: "936807a1-3f9b-11e9-b2b9-c54f58764873"
}
}]
svg.selectAll('path:not([elementType=temp-path])').data(myEdges)
.enter().append('path')
.attr("fill", "none")
.attr("stroke", "blue")
.style("stroke-width", "2px")
.attr('dummy', function(d) {
console.log("dummy here: " + d);
return d;
})
.attr('d', d3.linkVertical()
.x(function(d) {
console.log(d);
return d.in;
})
.y(function(d) {
return d.out;
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>
最后,这些其他答案可能会帮助您理解链接生成器所需的数据结构:https://stackoverflow.com/a/44760465/5768908和 https://stackoverflow.com/a/51424331/5768908
关于javascript - 创建路径时丢失数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55013146/