如何使用 d3 选择特定的父级?

Kin*_*rog 5 d3.js

我想选择可能高几级的父节点。我如何用 d3 做到这一点?

<div class="parent">
   <div class="stepson">
       <div class="child">
            Wassup Fatso?
       </div>
   </div>
</div>

d3.select('.child').parent('.parent')....? //I would like to go up the dom to a element with class parent.
Run Code Online (Sandbox Code Playgroud)

alt*_*lus 5

查找与某个选择器字符串匹配的父元素的最简单方法是使用以下Element.closest()方法:

Element本身开始,该closest()方法遍历 的父Element节点(朝向文档根),直到找到与提供的 selectorString 匹配的节点。

要将其保留在 D3 宇宙中,您可以使用该selection.select()方法,该方法接受一个选择器函数作为其参数:

如果选择器是一个函数,它会按顺序为每个选定元素计算,传递当前数据 ( d )、当前索引 ( i ) 和当前组 ( nodes ),并将this作为当前 DOM 元素 (主题节点)。它必须返回一个元素,如果没有匹配的元素,则返回 null。

在孩子的选择上调用此方法,您将可以访问孩子的 DOM 元素,该元素由this. 从那里你可以很容易地找到你所追求的父元素:

const parent = child.select(function() {
  return this.closest(".parent");  // Get the closest parent matching the selector string.
});
Run Code Online (Sandbox Code Playgroud)

查看以下可执行演示的片段:

const parent = child.select(function() {
  return this.closest(".parent");  // Get the closest parent matching the selector string.
});
Run Code Online (Sandbox Code Playgroud)
const child = d3.select(".child");  // Select the child.

const parent = child.select(function() {
  return this.closest(".parent");   // Get the closest parent matching the selector string.
});

console.log(parent.node());         // <div class="parent">…</div>
Run Code Online (Sandbox Code Playgroud)


Eri*_*uan 1

我不认为 D3 提供了类似 jQuery 的选择器。您也许可以通过本机 dom 选择器来完成此操作。

var parent = d3.select('.child').node().parentNode.parentNode
Run Code Online (Sandbox Code Playgroud)

然后您可以像这样检索该节点的数据

d3.select(parent).datum()
Run Code Online (Sandbox Code Playgroud)