如何使用d3.js获取parentNode的索引i [英] how to get a parentNode's index i using d3.js

查看:857
本文介绍了如何使用d3.js获取parentNode的索引i的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用d3.js,在我使用父节点的某个值x之后,我会使用:

Using d3.js, were I after (say) some value x of a parent node, I'd use:

d3.select(this.parentNode).datum().x

但是,是数据(即数据)的索引。建议?

What I'd like, though, is the data (ie datum's) index. Suggestions?

谢谢!

推荐答案

元素的索引只有在集合中定义良好。当你只选择一个元素时,没有集合,并且索引的概念没有真正定义。例如,您可以创建一些 g 元素,然后对不同(重叠)子集应用不同的操作。任何单独的 g 元素将有几个索引,取决于您考虑的子集。

The index of an element is only well-defined within a collection. When you're selecting just a single element, there's no collection and the notion of an index is not really defined. You could, for example, create a number of g elements and then apply different operations to different (overlapping) subsets. Any individual g element would have several indices, depending on the subset you consider.

're想实现,你必须保持一个参考你要使用的具体选择。有了这个和标识元素的东西,你可以做这样的事情。

In order to do what you're trying to achieve, you would have to keep a reference to the specific selection that you want to use. Having this and something that identifies the element, you can then do something like this.

var value = d3.select(this.parentNode).datum().x;
var index = -1;
selection.each(function(d, i) { if(d.x == value) index = i; });

这依赖于具有唯一标识元素的属性。

This relies on having an attribute that uniquely identifies the element.

如果您只有一个选择,您可以将索引另存为另一个数据属性,稍后再访问。

If you have only one selection, you could simply save the index as another data attribute and access it later.

var gs = d3.selectAll("g").data(data).append("g")
  .each(function(d, i) { d.index = i; });
var something = gs.append(...);
something.each(function() {
  d3.select(this.parentNode).datum().index;
});

这篇关于如何使用d3.js获取parentNode的索引i的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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