我是d3的新手,而且还在学习。我将节点和链接作为d3中的变量,从给定的json数据格式/graph中选择各自的节点和链接。我编写了一个函数,根据每个链接的源、和目标名称更改其颜色。
我无法理解的是,在变量节点上调用此函数也会改变链接的颜色。那么,我在哪个对象上调用这个函数,有什么关系吗?d变量是否根据我所调用的函数在内部从节点更改为链接?
代码
//How link is defined
var link=svg
.append("g")
.selectAll("line")
.data(graph.links)
.enter()
.append("line")
.attr("stroke-width",function(d){
return 3
})
.style("stroke","pink")
.text("text",function(d){return d.name});
//How node is defined
var node =svg
.append("g")
.selectAll("circle")
.data(graph.nodes)
.enter()
.append("circle")
.attr("r",5)
.attr("fill", function(d){
return "orange"
})
.attr("stroke","yellow")
;
//link.call(updateState1)
//This works as it should
node.call(updateState1)
// I can't understand why this line works too.
function updateState1() {
link
.each(function(d) {
var colors=["red","green","blue"]
var num=0;
if(d.source.name.length>d.target.name.length)
{
num=1;
console.log("Inside 1");
console.log("Source is ",d.source.name," and target is ",d.target.name);
}
else if(d.source.name.length<d.target.name.length)
{
num=2;
console.log("Inside 2");
console.log("Source is ",d.source.name," and target is ",d.target.name);
}
else{
num=0;
}
// your update code here as it was in your example
d3
.select(this)
.style("stroke", function(d){ return colors[num]})
.attr('marker-end','url(#arrowhead)');
});
}发布于 2020-01-15 18:38:56
使用selection.call时,函数的第一个参数是调用它的selection。所以如果你看看:
function updateState1() {
link
.each(function(d) {您可以看到您正在显式地使用link,这就是链接被更新的原因。相反,如果将其更改为:
function updateState1(selection) {
selection
.each(function(d) {它应该使用selection.call中的选择(node在node.call(updateState1)的情况下)。
如果传递给selection.call的函数不带任何参数,则相当于调用函数本身(也就是说,如果fn没有任何参数,selection.call(fn)与fn()相同)。
https://stackoverflow.com/questions/59757537
复制相似问题