简体   繁体   中英

How can I toggle the value of an svg text element with D3.js when user clicks the text?

I have just started to learn D3.js and have written a small program to test some ideas that I plan to implement in a larger program. Referring to the code here, the initial value of the text is 0. I am trying to have the value toggle between 1 and 0 when a user clicks on the text. There is something wrong with what I've coded in .on(“click”…) because the text does not change to 1. What am I doing wrong?

I've found examples of updating .attr, but I can't find anything about toggling .text in the manner I want.

            var txt1 = g.append("text")
                        .attr("id", "txt1")
                        .text("0")
                        .attr("x", 10)
                        .attr("y", 17)
                        .attr("font-family", "Arial")
                        .attr("font-size", "12")
                        .attr("fill", "black")   
                        .on("click", function(){
                            if (d3.select(this).text === "0"){
                                d3.select(this).text("1")
                            }
                            else{
                                d3.select(this).text("0");
                            }
                        } )

When I click on the text element the first time I expect to see it change to "1".

To get the text content of the SVG element directly you can use textContent or innerHTML in modern browsers. For instance:

 var svg = d3.select("svg") var txt1 = svg.append("text") .text("0") .attr("x", 10) .attr("y", 20) .on("click", function() { console.log(this.textContent) }) 
 <script src="https://d3js.org/d3.v5.min.js"></script> <svg></svg> 

However, because you're using a D3 selection , not an SVG node, you should use text as a getter, which is text() . By the way, text() internally uses textContent :

export default function(value) {
  return arguments.length
      ? this.each(value == null
          ? textRemove : (typeof value === "function"
          ? textFunction
          : textConstant)(value))
      : this.node().textContent;
}

Finally, you don't need that if block. To toggle between 0 and 1 , just do:

this.textContent = 1 - (+this.textContent);

You can even drop the unary plus, since the string will be converted to a number anyway:

this.textContent = 1 - this.textContent;

Here is the snippet:

 var svg = d3.select("svg") var txt1 = svg.append("text") .text("0") .attr("x", 10) .attr("y", 20) .on("click", function() { this.textContent = 1 - (+this.textContent); }) 
 <script src="https://d3js.org/d3.v5.min.js"></script> <svg></svg> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM