gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:41:49 27 4
gpt4 key购买 nike

我想选择可能高几级的父节点。我如何用 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.

最佳答案

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

Starting with the Element itself, the closest() method traverses parents (heading toward the document root) of the Element until it finds a node that matches the provided selectorString.



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

If the selector is a function, it is evaluated for each selected element, in order, being passed the current datum (d), the current index (i), and the current group (nodes), with this as the current DOM element (nodeson-topic). It must return an element, or null if there is no matching element.



在 child 的选择上调用此方法,您可以访问 child 的 DOM 元素,该元素由 this 引用。 .从那里你可以很容易地找到你所追求的父元素:
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>

关于d3.js - 如何使用 d3 选择特定的父级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43689909/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com