简体   繁体   中英

d3 successive creation of nodes with selectAll().data().enter().append()

I'm currently trying to create 2 times the number of nodes provided by an array in d3. The second time I try to create nodes with the same structure, the nodes are not created. I'm not familiar enough with d3 to understand why, and I'm hoping someone can help before I dig through the docs.

Example.

data = [1,2,3,4]

var someTag = d3.select("svg")
.append("div")
.attr("id","outer-div");

// this successfully creates the elements
someTag.select("div")
.data(data)
.enter().append("div")
.attr("id", function(d) { return d; }

// this does not create the elements
someTag.select("div")
.data(data)
.enter().append("div")
.attr("id", function(d) { return d*10; }

the goal is to have:

<div id="outer-div">
<div id="1"></div>
<div id="2"></div>
...
<div id="10"></div>
<div id="11"></div>
...
<div id="20"></div>
</div>

Try to select different elements (using selectAll instead of select ):

someTag.selectAll("foo")
    .data(data)
    .enter().append("div")
    .attr("id", function(d) { return d; });

someTag.selectAll("bar")
    .data(data)
    .enter().append("div")
    .attr("id", function(d) { return d*10; });

You can literally select elements, classes or IDs that don't exist, as I did here with foo and bar .

Here is a demo:

 var data = [1,2,3,4] var someTag = d3.select("body") .append("div"); someTag.selectAll("foo") .data(data) .enter().append("div") .html(d=>d); someTag.selectAll("bar") .data(data) .enter().append("div") .html(d=>d);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

PS : I'm only answering your question here, nothing more, but I have to say this: your code is not going to work. You cannot append a <div> to an SVG. Besides that, IDs cannot start with a number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM