how to get a parentNode's index i using d3.js

前端 未结 1 1517
情歌与酒
情歌与酒 2021-01-21 08:21

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 da

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-21 08:50

    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.

    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;
    });
    

    0 讨论(0)
提交回复
热议问题