Javascript 基于D3嵌套数据的条件追加
我有这样的数据:Javascript 基于D3嵌套数据的条件追加,javascript,d3.js,Javascript,D3.js,我有这样的数据: [ {id: 1, x:10, y:20, a: 123}, {id: 2, x:20, y:12}, ] <div style='top:20px; left: 10px'> <strong>1</strong> <span>123</span> </div> <div style='top:12px; left: 20px'> <strong>2</s
[
{id: 1, x:10, y:20, a: 123},
{id: 2, x:20, y:12},
]
<div style='top:20px; left: 10px'>
<strong>1</strong>
<span>123</span>
</div>
<div style='top:12px; left: 20px'>
<strong>2</strong>
</div>
我希望生成的DOM如下所示:
[
{id: 1, x:10, y:20, a: 123},
{id: 2, x:20, y:12},
]
<div style='top:20px; left: 10px'>
<strong>1</strong>
<span>123</span>
</div>
<div style='top:12px; left: 20px'>
<strong>2</strong>
</div>
1
123
2
有没有一种方法可以根据属性的存在来追加元素?
如果新版本的数据缺少这些属性,还有一种删除它们的方法?是的,您可以使用子选择 以下是生成所需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()
将其附加到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>
我的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、strong、span)的块都是d3中的直接应用程序。我们先退出,然后进入,最后更新——这是模式的常见变体
parent.exit().remove(); //exit
parent.enter().append("div"); //enter
parent.style({
"top" : function (d) { return d.y} ,
"left" : function (d) { return d.x }
}); //update
子选择是魔术发生的地方(参见)。传递给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] : [] });
回答得很好。完整的示例(不仅仅是代码片段)和重要部分的解释。
// 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] : [] });