我刚刚开始使用D3进行网络应用,以便可视化图表。我的边和节点是可点击的。节点在双击时将用户发送到包含有关节点信息的表。我想对边缘做同样的事情,所以当点击时。我想检索到该边缘的相应节点,以便我可以将该信息发送到另一个脚本。
从技术上讲,我想知道的是如何检索与边缘对应的节点的名称。例如。节点A连接到节点B.如何在边缘(链接)上单击时检索节点信息?输出应该是值A和B.我查看了所有内容,但我无法找到任何相关信息。
我的边缘和节点信息位于JSON文件中
d3.dataset = {
"nodes":[
{"name":"heart problems","group":"1"},
{"name":"acetic acid","group":"3"},
{"name":"alzheimers","group":"1"},
{"name":"bipolar","group":"1"},
{"name":"ebola","group":"1"},
{"name":"vaccinium myrtillus","group":"2"},
{"name":"adamantane","group":"3"},
{"name":"fluorene","group":"3"}
],
"links":[
{"source":3,"target":1,"value":20},
{"source":3,"target":6,"value":20},
{"source":3,"target":7,"value":9},
{"source":0,"target":1,"value":19},
{"source":0,"target":6,"value":1},
{"source":2,"target":1,"value":20},
{"source":2,"target":6,"value":20},
{"source":2,"target":7,"value":5},
{"source":4,"target":1,"value":2},
{"source":4,"target":6,"value":3},
{"source":2,"target":5,"value":2},
{"source":5,"target":1,"value":2}
]
}
解决方案,谢谢你的答案,我感觉很蠢......我忘了在功能中使用d:)
现在这是函数,clickonEdgeEvent函数将值传递给我的HTML
var clickOnEdge = svg.selectAll(".link").on("dblclick", function(d){
d3.select(this).attr('r', 8)
.style("fill","lightcoral")
.style("stroke","red")
clickonEdgeEvent((d.source.name),(d.target.name));
});
先谢谢你的帮助, 达尼
答案 0 :(得分:1)
所以你只想获得边连接的节点?这将有效:
//take it you have an on click function
.on('click',function(d){
var connectedNodes = nodes.filter(function(e){
return e.id == d.source.id || e.id == d.target.id; //connected nodes
})
})
上面的代码将返回与链接的源ID和目标ID匹配的节点。如果您以其他方式链接它们,只需更改过滤器:)
实施小提琴:https://jsfiddle.net/thatOneGuy/0nv4ck58/4/
我嘲笑小提琴作为例子。虽然我使用鼠标悬停,而不是点击。而不是ID我需要使用Name。只需确保在您的情况下使用唯一值进行比较。这是主要部分:
.on('mouseover', function(d) {
console.log(d)
var connectedNodes = node.filter(function(e) {
return e.name == d.source.name || e.name == d.target.name; //connected nodes
}).style('stroke', 'red')
.attr('r', 15)
})
.on('mouseout', function(d) {
console.log(d)
var connectedNodes = node.filter(function(e) {
return e.name == d.source.name || e.name == d.target.name; //connected nodes
}).style('stroke', 'white')
.attr('r', 5)
})
在此示例中,在鼠标悬停链接上,连接的节点将显得更大并带有红色边框。 Mouseout恢复正常:)