admin管理员组

文章数量:1196423

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?

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?

Share Improve this question asked May 20, 2013 at 19:55 IsaacIsaac 2,7214 gold badges32 silver badges47 bronze badges 1
  • 2 I don't know about d3, but I noticed you're setting the text as html code. Can't you do something like .html or .innerHTML instead of .text() ? – BBog Commented May 20, 2013 at 20:04
Add a comment  | 

1 Answer 1

Reset to default 23

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;
       })

本文标签: javascriptHow to return html in d3 text functionStack Overflow