可以在追加/插入后输入()选择重复使用吗? [英] Can enter() selection be reused after append/insert?

查看:130
本文介绍了可以在追加/插入后输入()选择重复使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,我想使用数据连接为每个数据元素添加2个新元素。

I have a scenario where I want to use a data join to append 2 new elements for each data element.

我最初是这样做的: p>

I was originally doing something like this:

var y = d3.selectAll("line")
    .data([123, 456]);

y.enter().append("line");  // assume attr and style set
y.enter().append("line");

y.transition()...

,我期望在我的转换中使用的更新选择将包含从输入选择合并的附加。但是,这当然没有工作,因为每个数据元素的选择只有一个插槽。

Before I thought it through, I was expecting that the update selection used in my transition would contain the merged appends from the enter selection. But of course this did not work because there's only 1 slot in the selection per data element.

所以我改变了代码,使它仍然使用相同的enter两次,然后重新选择新的元素为了做转换。

So I changed the code such that it still used the same enter() selection twice but then reselected for the new elements in order to do the transition.

这种方法工作,但我的问题是,这是否是一个推荐的方式去。我应该确保在我追加/插入后停止使用enter()?或者是确定使用它创建多个元素,只要我记得更新选择将只包含最后创建的元素?

This approach worked, but my question is whether or not this is a recommended way to go about things. Should I make sure to stop using enter() after I append/insert? Or is it OK do use it to create multiple elements as long as I remember that the update selection will only contain the elements created last?

如果它确实证明,是错误的,什么是更好的方法来实现这个?

If it does turn out that this is wrong, what is a better way to achieve this?

推荐答案

数据加入的目的是将元素与数据同步,创建,删除或更新元素有必要的。如果你创建元素两次,元素将不再与绑定数据数组一一对应。

No. The purpose of the data-join is to synchronize elements with data, creating, removing or updating elements as necessary. If you create elements twice, the elements will no longer correspond one-to-one with the bound array of data.

如果你想要两个元素对应每个基准,然后首先附加组(G)元素,以建立从数据到元素的一对一映射。然后根据需要追加子元素。结果结构如下:

If you want two elements to correspond to each datum, then append a group (G) element first to establish a one-to-one mapping from data to elements. Then append child elements as necessary. The resulting structure is like this:

<g>
  <line class="line1"></line>
  <line class="line2"></line>
</g>
<g>
  <line class="line1"></line>
  <line class="line2"></line>
</g>

例如:

var g = svg.selectAll("g")
    .data([123, 456]);

var gEnter = g.enter().append("g");
gEnter.append("line").attr("class", "line1");
gEnter.append("line").attr("class", "line2");

这篇关于可以在追加/插入后输入()选择重复使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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