javascript - 如何访问 D3.js 版本 4 中的节点 x 和 y?

标签 javascript d3.js

我尝试按照这个示例并使用 D3.js 绘制树布局:

https://bl.ocks.org/d3noob/08ecb6ea9bb68ba0d9a7e89f344acec8

我收到错误“属性 d:预期数字,“Mundefined,未定义””和“属性转换:预期数字,“翻译(未定义,未定义)””。

当我尝试记录 d.x 和 d.y 时,我得到了未定义的结果:

var link = g.selectAll(".link")
    .data( nodes.descendants().slice(1))
  .enter().append("path")
.attr("class", "link")
.style("stroke", function(d) { return d.data.level; })
.attr("d", function(d) {
   console.log(d.x, d.y) // undefined undefined
   return "M" + d.y + "," + d.x
     + "C" + (d.y + d.parent.y) / 2 + "," + d.x
     + " " + (d.y + d.parent.y) / 2 + "," + d.parent.x
     + " " + d.parent.y + "," + d.parent.x;
   });

如何获取节点 x 和 y 值?或者我需要将它们分配到某个地方吗?

另外,我在示例中没有得到的是 selectAll 不应该获取现有元素吗?这段代码让我感到困惑,因为我认为这是生成链接的地方,但另一方面它使用 selectAll 方法来“.link”。那么这里究竟发生了什么?

最佳答案

How do I get the node x and y values? Or do I need to assign them somewhere?

在您的代码中,xy 值源自 nodes.descendants().slice(1),它用作.data() 中的参数。因此,您在 nodes.descendants().slice(1) 中拥有的任何 xy 值都可以在以后使用。

Also what I don't get in the example is that isn't the selectAll supposed to get the existing elements?

释义一个伟大的tutorial :

So you might imagine something like this would be helpful

var link = g.selectAll(".link")

and you’d be right, but there’s a catch: The paragraphs we want to select don’t exist yet. And this gets at one of the most common points of confusion with D3: How can we select elements that don’t yet exist? Bear with me, as the answer may require bending your mind a bit.

链接尚不存在,但您的 enter() 命令创建了它们

关于javascript - 如何访问 D3.js 版本 4 中的节点 x 和 y?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41023171/

相关文章:

javascript - 我怎样才能看到代表应用了悬停的栏的当前元素

SVG 是不可见的,但存在于 DOM 中

javascript - 识别 D3.js 图

javascript - 为什么 Date.prototype.toString() 和 Date.prototype.toLocaleString() 会返回表示不一致时间点的字符串?

javascript - 完全相同的代码在 Dreamweaver 中无法正常工作

javascript - 将 DOM 对象附加到 qunit-fixture + Qunit

javascript - 由 Json 填充的组合框

php - 表达式引擎 - PHP - 无法运行函数

javascript - 如何在 D3.js 中读取 Blob

javascript - 鼠标悬停在d3.js中,如何获取相应位置的值?