使用D3.js创建嵌套的HTML结构 [英] Creating nested HTML structures with D3.js

查看:2216
本文介绍了使用D3.js创建嵌套的HTML结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象看起来像这样:

I have an object that looks something like this:

data = {
  questions: [ 
               value: "Question 1", answers: [ {value:"answer1"}, {value:"answer2"} ],
               value: "Question 2", answers: [ {value:"answer1"}, {value:"answer2"} ]
             ]
}

简化 - 答案有一个计数,将使用条形图显示)。

(This is simplified - answers have a count that will be displayed using bar graphs. I think I know how to do that once I get there, however.)

我的问题有动态(因为数据变化频繁)创建HTML结构,应该看起来像这样:

The issue I'm having is dynamically (because the data changes frequently) creating the HTML structure, which should look something like this:

<div class="question">
  Question 1  
  <div class="answer">Answer 1</div>
  <div class="answer">Answer 2</div>
</div>
<div class="question">
  Question 2  
  <div class="answer">Answer 1</div>
  <div class="answer">Answer 2</div>
</div>

我可以得到D3来创建问题div =question),并放入文本中(即问题1等),但我不知道如何得到D3创建一个子div的答案即

I can get D3 to create the question divs (the ones w/ class="question"), and put in the text for that (i.e. "Question 1", etc.) but I can't figure out how to get D3 to create a child div for the answers (i.e. the ones w/ class="answer").

这是我现在的状态:

var questions_chart = d3.select('#survey-questions')
    .selectAll("div")
    .data(data.questions);

questions_chart.transition()
    .text(function(d) { return d.value; });

questions_chart.enter().append("div")
    .text(function(d) { return d.value; })
    .attr("class", "question rounded")

questions_chart.exit().remove();

基本上,我如何嵌套D3附加,这样我可以嵌套 c>

Basically, how can I nest D3 appends in such a way that I can nest divs for each answer within the div for that question?

推荐答案

如Lars所示,您要为此使用嵌套选择:

As Lars indicated, you want to use nested selections for this:

var data = {
  questions: [ 
    {value: "Question 1", answers: [ {value:"answer1"}, {value:"answer2"} ]},
    {value: "Question 2", answers: [ {value:"answer1"}, {value:"answer2"} ]}
  ]
};

d3.select("body").selectAll("div")
  .data(data.questions)
  .enter().append("div") // this creates the question divs
    .text(function(d) { return d.value; })
  .selectAll("div")
  .data(function(d) { return d.answers; })
  .enter().append("div") // this creates the nested answer divs
    .text(function(d) { return d.value; });

注意:我不得不修复你的数据,使 data.questions 一个对象数组。

Note: I had to fix your data a little, making data.questions an array of objects.

这篇关于使用D3.js创建嵌套的HTML结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆