D3.js 在节点选择上突出显示链接

D3.js Highlighting links on node selection

所以首先,我有格式与下面 miserables.json 相同的数据 https://bl.ocks.org/mbostock/4062045

我希望能够在单击节点时使连接到我的节点的 link 变为红色。 所以伪代码就像

selectAll(.links)
if links.source=nodeID or links.target=nodeID
then links.color=red

但是我做不到。我的最终目标是将它与下面的 Arc 图集成 http://bl.ocks.org/sjengle/5431779

您的伪代码是一个好的开始。您可以使用 filter 在选择中实现 if 条件。注意链接的.source.target是d3编辑的,不再是节点的id,而是节点本身:

thisNode = nodeObject; // where nodeObject is the javascript object for the node, it's probably called "d" in your function.
d3.selectAll(".link")
  .filter(function(d) {
     return (d.source === thisNode) || (d.target === thisNode);
   })
  .style("stroke", "red")

在@laurent 的回答之上扩展到 "reset" 可能在之前的交互中被涂成红色的链接颜色:

thisNode = nodeObject; // where nodeObject is the javascript object for the node, it's probably called "d" in your function.
d3.selectAll(".link")
  .style("stroke",function(d) {
     return d.source === thisNode || d.target === thisNode ? "red" : "#888888";
   })