简体   繁体   English

使用d3和.data()输入文本

[英]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): 我已经创建了一个div,就像这样(#stats_data div已经存在):

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

It's now in the DOM. 现在在DOM中。

Now I would like to change that text based inside a D3.json function. 现在,我想基于D3.json函数更改该文本。 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.select更改文本,但数据绑定功能无法运行。

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.. 我们什么也没有,没有console.log或其他任何东西。

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). 您的第一个片段在做正确的事情,在DOM上选择要修改的元素,但我会将其重写为变量(并删除626文本)。 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. 然后,再次选择它时,只需参考aDiv。 In the next part you need to bind the data to the new elements you are creating with d3. 在下一部分中,您需要将数据绑定到使用d3创建的元素。 So you need to use enter() . 因此,您需要使用enter() You also have to tell d3 what to create or append . 您还必须告诉d3创建或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): 假设您对data/statsdata.json调用返回一个对象(而不是对象数组):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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