【问题标题】:Creating nested HTML structures with D3.js使用 D3.js 创建嵌套的 HTML 结构
【发布时间】:2014-03-13 21:11:38
【问题描述】:

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

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

(这是简化的 - 答案有一个计数,将使用条形图显示。不过,我想我知道一旦我到达那里该怎么做。)

我遇到的问题是动态(因为数据经常更改)创建 HTML 结构,它应该看起来像这样:

<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(带有class="question" 的那些),并为此输入文本(即“问题 1”等),但我不知道如何获得 D3为答案创建一个子 div(即带有 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 附加项,以便我可以在 div 中为该问题的每个答案嵌套 divs

【问题讨论】:

标签: javascript html d3.js


【解决方案1】:

正如 Lars 所指出的,您希望为此使用嵌套选择:

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 成为一个对象数组。

【讨论】:

  • 无论如何,我的意思是问题是一组对象。非常感谢!
  • 另一个问题:我将如何/在哪里放置 .exit() 或 .transition() 作为答案?在我的原始代码中,我将主图表保存在一个变量中(questions_chart),所以我可以说类似questions_chart.exit().remove()。但是,如果我将 .exit().remove() 放在 .text() 之后(代码中的最后一行),我会收到一条错误消息,指出 object array has no method 'exit'
【解决方案2】:

这扩展了彼得给出的答案,以添加您在原始问题中请求的“类”信息,并在评论中回答您的后续问题:

var divQ = d3.select("body").selectAll("div")
    .data(data.questions);

divQ
    .enter()
    .append("div") // this creates the question divs
    .attr("class","question")
    .text(function(d) { return d.value; });

divQ
    .exit()
    .remove();


var divA = divQ.selectAll("div")
    .data(function(d) { return d.answers; });

divA
    .exit()
    .remove();

divA
    .enter()
    .append("div") // this creates the nested answer divs
    .attr("class","answer")
    .text(function(d) { return d.value; });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 2019-05-22
    • 1970-01-01
    相关资源
    最近更新 更多