Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

javascript - How to return html in d3 text function?

I want to be able to return html from the text function like this:

textEnter.append("tspan")
          .attr("x", 0)
          .text(function(d,i) {
             return 'some text' + '<br/>' + d.someProp;
           })

Tried to use &lt;br&gt;, but didnot work. How do I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

EDITED ANSWER

Just noticed that you're working with a tspan here. Unfortunately you can't insert line breaks into svg text elements. Multiline text with SVG requires breaking up the text yourself and then laying it out by setting the dy attribute. D3 makes the laying out process pretty straight forward, but it still takes extra work.

More info in the intro paragraph here: http://www.w3.org/TR/SVG/text.html

OLD ANSWER (applies if using html elements, not svg)

D3 has a separate method for this: the html() method, which works just like text() but unescaped. More info here. So, easily enough, you just need:

textEnter.append("tspan")
      .attr("x", 0)
      .html(function(d,i) {
         return 'some text' + '<br/>' + d.someProp;
       })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...