如何根据D3中的数据创建元素? [英] How to create elements depending on data in D3?

查看:132
本文介绍了如何根据D3中的数据创建元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看示例:

d3.select("body").selectAll("div")
    .data([4, 8, 15, 16, 23, 42])
  .enter().append("div")
    .text(function(d) { return d; });

不能提供帮助,但想知道如何使附加信息对提供的数据敏感-用某些谓词说do append and fill text其他观点说do append and fill text不要追加?

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?

推荐答案

最简单的方法是在调用.data( ... )之前过滤您的数组:

The simplest way is to filter your array before calling .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; });

只会为4和8创建一个div.

will create a div only for 4 and 8.

或者,在将数组绑定到页面上的元素以有条件地创建子元素之后,您可以过滤选择内容:

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

这篇关于如何根据D3中的数据创建元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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