gpt4 book ai didi

javascript - 如何通过 onClick 更改多个 SVG 节点的颜色

转载 作者:行者123 更新时间:2023-11-28 00:31:23 26 4
gpt4 key购买 nike

我正在构建一个应用程序,根据不同节点的特征将其链接在一起。数据结构[来自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');
}
});
});

最佳答案

您无法通过数据选择元素。但是,您可以过滤选择:

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

关于javascript - 如何通过 onClick 更改多个 SVG 节点的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28954327/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com