根据D3的嵌套数据有条件地追加
Conditionally appending based on nested data with D3
我有这样的数据:
[
{id: 1, x:10, y:20, a: 123},
{id: 2, x:20, y:12},
]
我想生成的DOM看起来像这样:
<div style='top:20px; left: 10px'>
<strong>1</strong>
<span>123</span>
</div>
<div style='top:12px; left: 20px'>
<strong>2</strong>
</div>
是否有一种方法可以根据属性的存在追加元素?
如果新版本的数据缺少这些属性,还有一种方法可以删除它们?
是的,你可以使用子选项。
下面是生成所需DOM的函数:
function show(arr) {
//bind data to divs
parent = d3.select("body").selectAll("div")
.data(arr);
//enter-update-exit pattern used to create divs
parent.exit().remove();
parent.enter().append("div");
parent.style({
"top" : function (d) { return d.y} ,
"left" : function (d) { return d.x }
});
//basic subselection bind
strong = parent.selectAll("strong")
.data(function(d) { return [d.id]});
//enter-update-exit
strong.exit().remove();
strong.enter().append("strong")
strong.text(String)
// subselection bind that handles missing attributes
span = parent.selectAll("span")
.data(function(d) { return d.a ? [d.a] : [] });
//enter-update-exit
span.exit().remove();
span.enter().append("span")
span.text(String)
}
我第一次打电话给show()
data1 = [
{id: 1, x:10, y:20, a: 123},
{id: 2, x:20, y:12},
{id: 3, x:15, y:15},
];
show(data1);
将此附加到DOM:
<div style="top: 20px; left: 10px;">
<strong>1</strong>
<span>123</span>
</div>
<div style="top: 12px; left: 20px;">
<strong>2</strong>
</div>
<div style="top: 15px; left: 15px;">
<strong>3</strong>
</div>
然后用
再次调用它data2 = [
{id: 1, x:10, y:20},
{id: 2, x:20, y:12, a: 123}
]
show(data2);
和DOM元素变成
<div style="top: 20px; left: 10px;">
<strong>1</strong>
</div>
<div style="top: 12px; left: 20px;">
<strong>2</strong>
<span>123</span>
</div>
将数据绑定到div的块很简单。不需要评论
parent = d3.select("body").selectAll("div")
.data(arr);
创建元素的块(div, strong, span)都是d3中进入-更新-退出习惯用法的直接应用。我们先执行exit,然后是enter,最后执行update——这是该模式的常见变体。
parent.exit().remove(); //exit
parent.enter().append("div"); //enter
parent.style({
"top" : function (d) { return d.y} ,
"left" : function (d) { return d.x }
}); //update
子选择是奇迹发生的地方(参见selection.data
的文档)。传递给data的函数将接收其父div绑定的数组中的元素(例如{id: 2, x:20, y:12}
)。该函数返回我们希望将子选择绑定到的任何元素(必须是一个数组)。对于强元素,我们只是抓取id并将其包装在一个数组中。
// parent datum {id: 2, x:20, y:12} becomes child data [2]
strong = parent.selectAll("strong")
.data(function(d) { return [d.id]});
对于span元素,当该属性的值存在时,将其包装在数组中,当它不存在时,仅返回一个空数组。
// parent datum {id: 1, x:10, y:20, a: 123} becomes [123]
// parent datum {id: 2, x:20, y:12} becomes []
span = parent.selectAll("span")
.data(function(d) { return d.a ? [d.a] : [] });
相关文章:
- 通过js在新选项卡中有条件地打开url
- jQuery-有条件地附加HTML
- 有条件更新d3.js力图中节点的最佳方法
- Woocommerce产品选项有条件
- 有条件地在选项标记中应用布尔属性
- ADF:有条件地加载javascript资源
- 如何有条件地更改角度中的orderBy参数
- 无法在有条件呈现的富:面板上提交h:form
- 有条件地与react路由器链接
- 有条件地运行javascript函数-Razor,HTML
- 如何使用图表包装函数有条件地格式化谷歌可视化表单元格
- CSS根据属性的可用性有条件地应用样式
- 将字段设置为有条件地使用所需的字段验证器
- 将https替换为有条件的锚标记Javascript
- JavaScript while循环没有'不能在有条件的情况下工作
- 如何用d3有条件地移除元素
- 有条件刷新页面-如何设置引用人
- 有条件地创建ajax url参数以与jQuery Validate一起使用
- 有条件地将查询字符串追加到角度 href
- 根据D3的嵌套数据有条件地追加