简体   繁体   中英

D3 text append will not display data

I am using d3 v4 and trying to use data as a text element.

In my index.html i have

<h3 id='my_text' class="text-center">
            This is my color:
        </h3>

And my d3 code is:

var data = [{"color":"red"}]

var txt = d3.select("#my_text")
      .append("text")

txt
  .data(data)
  .enter()
  .style("text-anchor", "start")
  .attr("fill", "black")
  .attr("y", 220)
  .attr("x", 30)
  .text( function (d) { return d.color; });

I expect to see This is my color: Red but I just see This is my color:

 I edit your code with some other exapmles <!DOCTYPE HTML> <html> <head> <script src="https://d3js.org/d3.v4.min.js"></script> </head> <body> <h3 id='my_text' class="text-center"> This is my color: </h3> <div id="d2">Second paragraph</div> <script> var pdata = [{ "color": "red" }]; d3.select("#my_text").style("color", "blue"); var txt = d3.select("#my_text") .append("p") .data(pdata) .text(function (d) { return d.color; }); </script> <script> d3.select("#d2").style("color", "red"); d3.select("#d2").append("div"); var matrix = [ [11975, 5871, 8916, 2868], [1951, 10048, 2060, 6171], [8010, 16145, 8090, 8045], [1013, 990, 940, 6907] ]; var tr = d3.select("body") .append("table") .selectAll("tr") .data(matrix) .enter().append("tr"); var tr = d3.select("body") .append("table") .selectAll("tr") .data(matrix) .enter().append("tr"); var td = tr.selectAll("td") .data(function (d) { return d; }) .enter().append("td") .text(function (d) { return d; }); </script> </body> </html> 

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