javascript 如何根据 D3 中的数据创建元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17723916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create elements depending on data in D3?
提问by DuckQueen
looking at sample:
看样品:
d3.select("body").selectAll("div")
.data([4, 8, 15, 16, 23, 42])
.enter().append("div")
.text(function(d) { return d; });
cant help but wonder how to make append sensitive to provided data - say do append and fill text
with some predicate say if d == 8
othervise do not append?
不禁想知道如何使附加对提供的数据敏感 -do append and fill text
用一些谓词说if d == 8
othervise不附加?
回答by Adam Pearce
The simplest way is to filter your array before calling .data( ... )
:
最简单的方法是在调用之前过滤数组.data( ... )
:
d3.select("body").selectAll("p")
.data([4, 8, 15, 16, 23, 42].filter(function(d){ return d < 10; }))
.enter().append("div")
.text(function(d) { return d; });
will create a div only for 4 and 8.
将为 4 和 8 创建一个 div。
Alternatively, you can filter your selection after binding your array to elements on the page to conditionally create children elements:
或者,您可以在将数组绑定到页面上的元素后过滤您的选择,以有条件地创建子元素:
d3.select("body").selectAll("div")
.data([4, 8, 15, 16, 23, 42])
.enter().append("div")
.text(function(d) { return d; })
.filter(function(d){ return d == 8; }).append("span")
.text("Equal to 8")