I am currently learning data visualizations with d3.js. I am using the tutorial on the d3.js site. I am at the part where the data bound to DOM elements have to retrieved. I did it exactly as they have shown, but I am not able to get the data from it. Here is the code from the beginning:
var theData=[1,2,3]
var p= d3.select("body")
.selectAll("p")
.data(theData)
.enter()
.append("p")
.text("hello")
This displays:
hello
hello
hello
Now, on the site, it tells me to enter the following code to obtain the data bound ie 1,2 & 3.
var theData=[1,2,3]
var p= d3.select("body")
.selectAll("p")
.data(theData)
.enter()
.append("p")
.text(function (d) { return d; } )
Even after doing this, the page does not change,like it should to:
1
2
3
It remains the same(it keeps showing the three hello's).
How do I get the data back?
When I try your code, it works (however, I am a all for pretty javascript, so I added ';' when approriate).
I would suggest checking out the console on the browsers developers tools (perhaps there are showing errors already) and change your code to something like this:
var theData=[1,2,3];
var p= d3.select("body")
.selectAll("p")
.data(theData)
.enter()
.append("p")
.text(function (d) {
console.log("checking d");
console.log(d);
return d;
} );
it would be really weird if you did not see at least "checking d" in your console...
when just using this :
var theData2 = [ 1, 2, 3 ]
var p2 = d3.select("body").selectAll("p")
.data(theData2)
.enter()
.append("p")
.text( function (d) {
console.log(d);
return d; } );
It works, you're using variables with the same names which you really shouldn't do
When our dataset contains more items than available DOM elements, the surplus data items are stored in a sub set of this selection called the enter selection. When you try to use enter
for the second time, there are already 3 elements and so no items are stored in enter selection. You should have used the same enter selection for both tasks.
var theData=[1,2,3] var p = d3.select("body") .selectAll("p") .data(theData); p.enter() .append("p") .text("hello"); p.enter() .append("p") .text(function (d) { return d; } );
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
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.