javascript 如何在d3文本函数中返回html?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16657319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:32:01  来源:igfitidea点击:

How to return html in d3 text function?

javascriptd3.js

提问by Isaac

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

我希望能够像这样从文本函数返回 html:

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?

尝试使用&lt;br&gt;,但没有奏效。我如何实现这一目标?

回答by meetamit

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 dyattribute. D3 makes the laying out process pretty straight forward, but it still takes extra work.

刚刚注意到你在这里使用 tspan 。不幸的是,您不能在 svg 文本元素中插入换行符。带有 SVG 的多行文本需要自己分解文本,然后通过设置dy属性进行布局。D3 使布局过程非常简单,但仍然需要额外的工作。

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

此处介绍段落中的更多信息:http: //www.w3.org/TR/SVG/text.html

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

旧答案(适用于使用 html 元素,而不是 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:

D3 对此有一个单独的方法:html()方法,它的工作原理类似text()但没有转义。更多信息在这里。因此,很容易,您只需要:

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