用D3.js创建嵌套的HTML结构
Creating nested HTML structures with D3.js
我有一个像这样的对象:
data = {
questions: [
value: "Question 1", answers: [ {value:"answerswer1"}, {value:"answerswer2"} ],
value: "Question 2", answers: [ {value:"answerswer1"}, {value:"answerswer2"} ]
]
}
(这是简化的-答案有一个计数,将使用条形图显示。不过,我想我一到那里就知道该怎么做了。
我遇到的问题是动态(因为数据经常变化)创建HTML结构,它应该看起来像这样:
<div class="question">
Question 1
<div class="answerswer">Answer 1</div>
<div class="answerswer">Answer 2</div>
</div>
<div class="question">
Question 2
<div class="answerswer">Answer 1</div>
<div class="answerswer">Answer 2</div>
</div>
我可以让D3创建问题div (w/class="question"
),并将其放入文本(即。"问题1"等),但我不知道如何让D3为答案(即那些w/class="answerswer"
)创建子div。
这是我现在的情况:
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
?
正如Lars所指出的,您希望使用嵌套选择:
var data = {
questions: [
{value: "Question 1", answers: [ {value:"answerswer1"}, {value:"answerswer2"} ]},
{value: "Question 2", answers: [ {value:"answerswer1"}, {value:"answerswer2"} ]}
]
};
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
的对象数组。
这扩展了Peter给出的答案,添加了您在原始问题中要求的"class"信息,并回答了您在评论中的后续问题:
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","answerswer")
.text(function(d) { return d.value; });
相关文章:
- TinyMCE保留预定义的html结构
- jQuery的HTML结构追加数组
- 正在创建嵌套的HTML结构
- 遍历HTML结构以搜索属性
- 如何用java脚本编写html结构
- 正在用jQuery改变HTML结构
- 如何从平面JavaScript数组创建分层HTML结构
- 如果有多个 ,请在后文条目时将新的 HTML 结构添加到
- 如何格式化 html 结构中特定符号内换行的文本并设置其格式
- 如何使用 jQuery 创建丰富的客户端体验时避免锁定我的 HTML 结构
- 在更改函数后使用 jQuery 选择对象,修改了需要选择的元素的 html 结构
- 无限滚动我的HTML结构
- DOM 不代表 d3 强制布局的 html 结构
- JQuery/Javascript - 突出显示文本并环绕标签,而无需更改 html 结构
- 在 HTML 结构中打印 JSON 数据问题
- 在使用Ajax仅检索数据库中的数据之间,如何更好地从html结构中的数据库中检索数据
- 在v-for中动态创建一个html结构
- jquery克隆了一个没有文本内容的html结构
- 如果序列与Html结构匹配,则需要Javascript
- 如果我的HTML结构包含另一个父HTML标记或id类等,则需要重定向