在 d3js 强制布局中更新某些节点的样式

Updating certain nodes' style in d3js force layout

更新已绘制节点样式的最简单方法是什么? 在这种情况下,布局已创建,所有链接、节点 - 完美。然后将一个数组传递给指令,如果节点名称在该数组中,我想更改其颜色。

示例:

var names = ["tom","john"]; // this data comes in...


                d3.select("node").select("circle").style("fill", function (d) {
                   // I check if the node name is in array, if so change its colour to green.
                    if (names.indexOf(d.name) > -1) {
                        return "green";
                    } else
                        return "red";

                });

尝试使用选择 filter

d3.selectAll("node").selectAll("circle")
  .filter(function(d){
    return names.indexOf(d.name) < 0;
  })
  .style("fill", "red");

艾哈迈德的方法很好。另一种选择:在构建页面时,将名称添加为 id 的值或每个节点的附加 class。然后你可以 select 使用那个 id 或 class 你想要的元素,也许用复合 CSS selector 。例如,如果你将名字命名为 ids,你可以这样做:

d3.selectAll("node").selectAll("#tom").style("fill", "green");

这里的“#tom”指的是所有DOM个带有id="tom"的元素。如果除了以 "tom" 作为 id 的圆圈之外,还有其他东西,这应该有效:

d3.selectAll("node").selectAll("circle#tom").style("fill", "green");

也就是说要用 id="tom" 得到 circles。

(可以将 #tom#john 与 select 中的某种 OR 运算符结合使用。我不确定。)