d3相当于jQuery parent()

Dar*_*ook 8 jquery svg d3.js

我有各种SVG <g>对象,每个对象都有一个<circle>孩子和一个<text>孩子.我可以使用附加到它的类select()来查找特定<text>对象,然后修改它:

d3.select('text.my-class')
    .classed("my-class",false).classed("new-class",true)
    .text("Next Stage!")
    ;
Run Code Online (Sandbox Code Playgroud)

现在我需要修改它的圆形兄弟.圆圈没有特定的识别类(嗯......也许给它一个d3方式这样做?),所以我的第一次尝试是类似jQuery:

d3.select('text.my-class').parent().select('circle')
    .attr('style','fill:#f00;')
    ;
Run Code Online (Sandbox Code Playgroud)

这失败了"父母不是一个功能".

建议使用类似问题的答案(如何选择d3.js中当前元素的父元素)this.parentNode,但要么我使用它错了要么在这里不起作用.我试过这两个:

d3.select('text.my-class').select(parentNode).select('circle')
d3.select('text.my-class').select(this.parentNode).select('circle')
Run Code Online (Sandbox Code Playgroud)

Pab*_*rro 12

D3没有访问父节点的方法.您可以使用该node()方法访问所选元素的DOM节点.该元素将具有以下parentNode属性:

var textNode = d3.select('text.my-class').node(),  // DOM node
    parentNode = textNode.parentNode,              // Parent DOM node
    parentSelection = d3.select(parentNode),       // Selection containing the parent DOM node
    circle = parentSelection.select('circle');     // selection containing a circle under the parent selection
Run Code Online (Sandbox Code Playgroud)

在回调中,您可以使用:

d3.select('text.my-class')
   .on('mouseover', function(d) {
      // The 'this' context is set to the DOM element, not the selection
      var circle = d3.select(this.parentNode).select('circle');
      circle.attr('fill', 'red');
   });
Run Code Online (Sandbox Code Playgroud)

问候,