如何从 onClick 更改多个 SVG 节点的颜色

How to change color of multiple SVG nodes from onClick

我正在构建一个应用程序,根据不同节点的特性将它们链接在一起。数据结构 [来自 Neo4j] 和前端设置 [D3] 是这样的:

graph.nodes 有 4 个属性:

1) id (字符串)

2) 姓名(字符串)

3)类型(字符串)

4) 属性(对象)

其中properties多了几个属性,但是对于这个问题,我们只考虑'properties.represents'

因此,当我单击一个节点时,我希望具有相同 'properties.represents' 的所有其他节点更改为相同的颜色(在本例中为蓝色)。

我尝试使用的具体代码是:

 getRep = n.properties.represents;

 graph.nodes.forEach(function(d) {
                    if (d.properties.represents == getRep) {
                        d3.select(d).style('fill', 'blue');
                    }
                });

然而,这是不正确的。控制台输出此错误消息:

未捕获类型错误:无法读取未定义的 属性'setProperty'

关于为什么这不起作用的任何建议?感谢您的宝贵时间,非常感谢。

    var link = svg.selectAll(".link")
            .data(graph.links).enter()
            .append("line").attr("class", "link");

    var node = svg.selectAll(".node")
            .data(graph.nodes).enter()
            .append("circle")
            .attr("class", function (d) { console.log("Represents: " + d.properties.represents); return "node "+ d.type.toString() })
            .attr("r", radius)
            .style("fill", function(d) {return d.colr; })
            .call(force.drag);

    // html title attribute
    node.append("title")
            .text(function (d) { return d.name; })

    var state = false;
    var last = null;
    var current = null;
    node.on("click", function(n)
            {

                var metainf = "";
                currRepresents = n.properties.represents;
                metainf = metainf.concat("Title: ", n.name, "<br/>Label: ", n.type);
                console.log(metainf);
                d3.select("#metainfo")
                    .html(metainf);

                last = current;
                current = d3.select(this);
                current.style('fill', 'red');
                last.style('fill', function(d) { return d.colr; });

                getRep = n.properties.represents;

                graph.nodes.forEach(function(d) {
                    if (d.properties.represents == getRep) {
                        d3.select(d).style('fill', 'blue');
                    }
                });
            });

您不能 select 元素的数据。但是,您可以过滤 selection:

svg.selectAll(".node")
   .filter(function(d) { return d.properties.represents == getRep; })
   .style('fill', 'blue');