简体   繁体   中英

Using d3 and .data() to enter text

This is very simple but it's not working for me.

See this example where it used to work..

I've created a div, like this (the #stats_data div is already existent):

d3.select('#stats_data')
        .append('div')
        .attr('id', 'stats_data5')
        .text("626")

It's now in the DOM.

Now I would like to change that text based inside a D3.json function. The code is so simple but it's not working at all. I know you can change text with d3.select but the data-bound function is not operation.

d3.json("data/statsdata.json", function(statsData){
    d3.select('#stats_data5')
    .data(statsData)
    .text( function(d){
            console.log('test');
        return d.year2012;
    });

We get nothing, not a console.log or anything..

What's the best approach?

Your first snippet is doing the right thing, selecting an element on the DOM to be modified, but I would rewrite it as a variable (and remove the 626 text). So something like:

var aDiv = d3.select('body')
    .append('div')
    .attr('id', 'stats_data5');

Then when you select it again all you need to do is refer to aDiv. In the next part you need to bind the data to the new elements you are creating with d3. So you need to use enter() . You also have to tell d3 what to create or append . So something like:

aDiv.selectAll("p")  //select all the empty p 
    .data(data)      // grab the data
    .enter()         // bind it to those previously empty p
  .append("p")       // add the p's t the DOM 
    .text( function(d){ // and you know what this does
        return d;
    });

You can see this all in this fiddle

Assuming your call to data/statsdata.json is returning an object (and not an array of objects):

var statsData5 = d3.select('#stats_data5');
d3.json("data/statsdata.json", function(statsData) {
  statsData5.text(statsData.year2012);
});

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