javascript 如何将文本附加到 D3 中的 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30518546/
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-28 12:19:08  来源:igfitidea点击:

How to append text to a div in D3

javascripthtmld3.js

提问by Kuan

All:

全部:

For example I have array of string:

例如我有字符串数组:

["string1","string2","string3","string4","string5"]

I want to add all of them into a div with
separate them like:

我想将它们全部添加到一个 div 中,
并将它们分开,例如:

<div>
string1<br>
string2<br>
string3<br>
string4<br>
string5
</div>

I wonder how to do it with D3? I am thinking use selectAll()...data()...enter().append(), but I do not know how to append this.

我想知道如何用 D3 做到这一点?我正在考虑使用 selectAll()...data()...enter().append(),但我不知道如何附加它。

Thanks

谢谢

回答by Mark

Data binding in d3is about appending an elementto the dom for each item in your data. What you are asking for, though, is how do I get one element with my strings separated by a <br/>:

数据绑定d3是关于为数据中的每个项目向 dom附加一个元素。但是,您要问的是如何使用由 a 分隔的字符串获取一个元素<br/>

  var arr = ["string1","string2","string3","string4","string5"];
  d3.select('body')
    .append('div')
    .html(arr.join('<br/>'));

A more d3ish way to get the same appearance is (but this gives you a div per string):

d3获得相同外观的更简单的方法是(但这会给每个字符串一个 div):

  var arr = ["string1","string2","string3","string4","string5"];

  d3.select('body')
    .selectAll('div')
    .data(arr)
    .enter()
    .append('div')
    .text(function(d){
      return d;
    });

A third approach is to use <span>s:

第三种方法是使用<span>s:

d3.select('body')
    .selectAll('span')
    .data(arr)
    .enter()
    .append('span')
    .text(function(d){
      return d;
    })
    .append('br');

Here's an examplewith both approaches.

这是两种方法的示例

回答by maioman

you should appendChild to the div;

你应该 appendChild 到 div;

try something like this(this is pure js !!!):

尝试这样的事情(这是纯 js !!!):

var myArray=["string1","string2","string3","string4","string5"];
var test = document.querySelector(".test")
myArray.forEach(function(x){
var textnode = document.createTextNode(x);
test.appendChild(textnode )
}) 

https://jsfiddle.net/maio/m3sqjjb3/

https://jsfiddle.net/maio/m3sqjjb3/