d3.js选择条件渲染 [英] d3.js selection conditional rendering

查看:199
本文介绍了d3.js选择条件渲染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用d3js连接模型,是否可以根据数据内容进行条件渲染?

Using the d3js join model, is it possible to do conditional rendering based on the data content?

我想做这样的事情:

var nodes = svg.selectAll('.node').data(nodes);

var node = nodes.enter().insert('svg:g').attr('class', 'node');

// if node.hasDuration {
   node.insert('svg:rect');
//} else {
   node.insert('svg:circle');
//}

nodes.exit().remove();

似乎没有一种使用联接模型(输入/退出)进行条件渲染的方法.我可以使用selection.each()对其进行暴力破解,但这似乎违背了选择模型的目的.

There doesn't seem to be a way using the join model (enter/exit) to have conditional rendering. I can brute force it with selection.each() but that seems to defeat the purpose of the selection model.

推荐答案

您可以使用过滤器:

var nodes = svg.selectAll('.node').data(nodes);

nodes.enter()
  .insert('svg:g')
  .attr('class', 'node');

nodes.filter(function(d,i){
  return d.hasDuration;
}).append('svg:rect');

nodes.filter(function(d,i){
  return !d.hasDuration;
}).append('svg:circle');

示例此处.

这篇关于d3.js选择条件渲染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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