根据D3的嵌套数据有条件地追加

Conditionally appending based on nested data with D3

本文关键字:有条件 追加 数据 嵌套 D3 根据      更新时间:2023-09-26

我有这样的数据:

[
  {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] : [] });