我正在使用强制布局的d3.js。现在,借助动态变化的数组data
,可以根据数组动态突出显示节点。同样使用下面的代码,我能够动态地显示节点的名称,这些节点是数组的一部分,作为文本。
因此,当阵列具有例如3个条目时,则显示3个节点,并且还出现3个节点名称。让我们说他们的名字是" a"," b"," c",所以文字" a",&# 34; b"," c"出现在屏幕上。
现在,当我点击新出现的文本" a",然后我希望包含该名称的节点填充为绿色。我用名为specialfunction
的函数尝试了这个。问题是,单击时所有节点都填充绿色
在文本" a"。你们中的某些人可以帮忙吗?感谢。
var texts = svg.selectAll(".texts")
.data(data);
textsExit = texts.exit().remove();
textsEnter = texts.enter()
.append("text")
.attr("class", "texts");
textsUpdate = texts.merge(textsEnter)
.attr("x", 10)
.attr("y", (d, i) => i * 16)
.text(d => d.name)
.on("click", specialfunction);
function specialfunction(d) {
node.style("fill", function(d){ return this.style.fill = 'green';});
};
答案 0 :(得分:2)
现在,您的specialFunction
函数仅选择nodes
并将其所有元素的样式设置为返回值...
this.style.fill = 'green';
......猜猜是什么,"green"
。
而不是filter
节点根据点击的文字:
function specialFunction(d) {
nodes.filter(function(e) {
return e === d
}).style("fill", "forestgreen")
}
在这个简单的演示中,d
是文本和圈子的编号。只需将我的演示中的d
更改为d.name
或您想要的任何其他媒体资源。单击文本,对应的圆圈将更改颜色:
var svg = d3.select("svg");
var data = d3.range(5);
var nodes = svg.selectAll(null)
.data(data)
.enter()
.append("circle")
.attr("cy", 50)
.attr("cx", function(d) {
return 30 + d * 45
})
.attr("r", 20)
.style("fill", "lightblue")
.attr("stroke", "gray");
var texts = svg.selectAll(null)
.data(data)
.enter()
.append("text")
.attr("y", 88)
.attr("x", function(d) {
return 26 + d * 45
})
.attr("fill", "dimgray")
.attr("cursor", "pointer")
.text(function(d) {
return d
})
.on("click", specialFunction);
function specialFunction(d) {
nodes.filter(function(e) {
return e === d
}).style("fill", "forestgreen")
}

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
&#13;
编辑:回答你的comment,这个更简单的功能可以将圆圈设置为原始颜色:
function specialFunction(d) {
nodes.style("fill", function(e){
return e === d ? "forestgreen" : "lightblue";
})
}
以下是演示:
var svg = d3.select("svg");
var data = d3.range(5);
var nodes = svg.selectAll(null)
.data(data)
.enter()
.append("circle")
.attr("cy", 50)
.attr("cx", function(d) {
return 30 + d * 45
})
.attr("r", 20)
.style("fill", "lightblue")
.attr("stroke", "gray");
var texts = svg.selectAll(null)
.data(data)
.enter()
.append("text")
.attr("y", 88)
.attr("x", function(d) {
return 26 + d * 45
})
.attr("fill", "dimgray")
.attr("cursor", "pointer")
.text(function(d) {
return d
})
.on("click", specialFunction);
function specialFunction(d) {
nodes.style("fill", function(e){
return e === d ? "forestgreen" : "lightblue";
})
}
&#13;
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
&#13;