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

gev0vcfq  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(47)

我想选择父节点,它可能比d3高几个级别。我该如何使用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.

字符串

3pmvbmvn

3pmvbmvn1#

找到匹配某个选择器字符串的父元素的最简单方法是使用Element.closest()方法:
Element本身开始,closest()方法遍历Element的父节点(指向文档根),直到找到与提供的selectorString匹配的节点。
要将其保留在D3宇宙中,您可以使用selection.select()方法,该方法接受选择器函数作为其参数:
如果 selector 是一个函数,它将对每个选中的元素进行计算,按顺序传递当前数据(d)、当前索引(i)和当前组(nodes),并将 this 作为当前DOM元素(nodes[i])。它必须返回一个元素,如果没有匹配的元素,则返回null。
在child的selection上调用这个方法,你可以访问this引用的child的DOM元素。从那里你可以很容易地找到你要找的父元素:

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

字符串
看看下面的可执行演示代码片段:

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>
<script src="https://d3js.org/d3.v5.js"></script>

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

的数据

ftf50wuq

ftf50wuq2#

我不认为D3提供了类似jQuery的选择器,你可以通过原生的dom选择器来实现。

var parent = d3.select('.child').node().parentNode.parentNode

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

d3.select(parent).datum()

相关问题