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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:22:14  来源:igfitidea点击:

How to create elements depending on data in D3?

javascriptd3.js

提问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 textwith some predicate say if d == 8othervise do not append?

不禁想知道如何使附加对提供的数据敏感 -do append and fill text用一些谓词说if d == 8othervise不附加?

回答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")