[英]How to append text to a div in D3
All: 所有:
For example I have array of string: 例如,我有一个字符串数组:
["string1","string2","string3","string4","string5"]
I want to add all of them into a div with 我想将所有这些添加到div中
separate them like: 将它们分开如:
<div>
string1<br>
string2<br>
string3<br>
string4<br>
string5
</div>
I wonder how to do it with D3? 我想知道如何用D3做到这一点? I am thinking use selectAll()...data()...enter().append(), but I do not know how to append this.
我在想使用selectAll()... data()... enter()。append(),但我不知道如何追加它。
Thanks 谢谢
Data binding in d3
is about appending an element to the dom for each item in your data. d3
数据绑定是关于将数据附加到数据中每个项目的dom。 What you are asking for, though, is how do I get one element with my strings separated by a <br/>
: 你问的是什么,不过,是怎么做的,我得到我的一个分隔的字符串一个元素
<br/>
:
var arr = ["string1","string2","string3","string4","string5"];
d3.select('body')
.append('div')
.html(arr.join('<br/>'));
A more d3
ish 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>
:
d3.select('body')
.selectAll('span')
.data(arr)
.enter()
.append('span')
.text(function(d){
return d;
})
.append('br');
you should appendChild to the div; 你应该将孩子附加到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/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.