How to manipulate nodes based on dynamicaly changing text? (enter/exit/update)

拈花ヽ惹草 提交于 2019-12-07 19:32:32

Right now, your specialFunction function is only taking the nodes selection and setting the style of all its elements to the returned value of...

this.style.fill = 'green';

... which is, guess what, "green".

Instead of that, filter the nodes according to the clicked text:

function specialFunction(d) {
    nodes.filter(function(e) {
        return e === d
    }).style("fill", "forestgreen")
}

In this simple demo, d is the number for both texts and circles. Just change d in my demo to d.name or any other property you want. Click the text and the correspondent circle will change colour:

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>

EDIT: Answering your comment, this even simpler function can set the circles to the original colour:

function specialFunction(d) {
    nodes.style("fill", function(e){
        return e === d ? "forestgreen" : "lightblue"; 
    })
}

Here is the demo:

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"; 
  })
}
<script src="https://d3js.org/d3.v4.min.js"></script>
    <svg></svg>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!