动态更新HTML页面文本基于所选的D3树节点。

huangapple go评论54阅读模式
英文:

Dynamically update html page text base don the d3 tree node selected

问题

以下是您要翻译的内容:

我有一个基于这个示例的工作中的D3可折叠树。我在我的HTML页面顶部(在一个单独的div中)添加了一个段落元素,我想根据用户点击的树节点更新文本。使用上面链接的示例,如果用户点击“analytics”节点,树应该展开以显示“analytics”的子节点,而我的页面顶部的段落文本应该更新为“analytics”。我的树运行良好,但我无法弄清如何更新段落文本。

我可以将这个段落文本更新为固定值,但不能根据点击的节点进行更新。

所以这个工作:

d3.select("p").text("这是段落。")

但这个不工作:

d3.select("p").text(function (d) {
  return d.name;
})

您能帮助吗?谢谢。

英文:

I have a working D3 collapsible tree based on this example. I have added a paragraph element at the top of my html page (in a separate div) that I want to update the text of based on the tree node a user clicks. Using the example linked above, if a user clicks on the "analytics" node the tree should expand to show children of "analytics" and the paragraph text at the top of my page should update to "analytics". My tree is working fine but I am not able to figure out how to update the paragraph text.

I am able to update this paragraph text to a fixed value but not based on the node clicked.

So this works:

d3.select("p").text("This is paragraph.")

but this does not:

d3.select("p").text(function (d) {
  return d.name;
})

Can you help with this? Thanks.

答案1

得分: 1

要更新 p 文本,您可以将 click 处理程序附加到节点上:

nodeEnter.on("click", (event, d) => {
    d.children = d.children ? null : d._children;
    update(d);
    d3.select("#node-info").text(d.data.name);
});

这是代码中的一部分,用于在单击节点时更新文本。

英文:

To update p text you can attach on click handler to the node:

nodeEnter.on("click", (event, d) => {
    d.children = d.children ? null : d._children;
    update(d);
    d3.select("#node-info").text(d.data.name);
  });

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    const data = {
      &quot;name&quot;: &quot;flare&quot;,
      &quot;children&quot;: [
        {
          &quot;name&quot;: &quot;analytics&quot;,
          &quot;children&quot;: [
            {
              &quot;name&quot;: &quot;cluster&quot;,
              &quot;children&quot;: [
                {&quot;name&quot;: &quot;AgglomerativeCluster&quot;, &quot;value&quot;: 3938},
                {&quot;name&quot;: &quot;CommunityStructure&quot;, &quot;value&quot;: 3812},
                {&quot;name&quot;: &quot;HierarchicalCluster&quot;, &quot;value&quot;: 6714},
                {&quot;name&quot;: &quot;MergeEdge&quot;, &quot;value&quot;: 743}
              ]
            },
            {
              &quot;name&quot;: &quot;graph&quot;,
              &quot;children&quot;: [
                {&quot;name&quot;: &quot;BetweennessCentrality&quot;, &quot;value&quot;: 3534},
                {&quot;name&quot;: &quot;LinkDistance&quot;, &quot;value&quot;: 5731},
                {&quot;name&quot;: &quot;MaxFlowMinCut&quot;, &quot;value&quot;: 7840},
                {&quot;name&quot;: &quot;ShortestPaths&quot;, &quot;value&quot;: 5914},
                {&quot;name&quot;: &quot;SpanningTree&quot;, &quot;value&quot;: 3416}
              ]
            },
            {
              &quot;name&quot;: &quot;optimization&quot;,
              &quot;children&quot;: [
                {&quot;name&quot;: &quot;AspectRatioBanker&quot;, &quot;value&quot;: 7074}
              ]
            }
          ]
        }
      ]
    };

    const width = 954;
    const dx = 10;
    const dy = width / 6;
    const margin = {top: 10, right: 120, bottom: 10, left: 40};

    const diagonal = d3.linkHorizontal().x(d =&gt; d.y).y(d =&gt; d.x);
    const tree = d3.tree().nodeSize([dx, dy]);

    const root = d3.hierarchy(data);

    root.x0 = dy / 2;
    root.y0 = 0;
    root.descendants().forEach((d, i) =&gt; {
      d.id = i;
      d._children = d.children;
      if (d.depth &amp;&amp; d.data.name.length !== 7) d.children = null;
    });

    const svg = d3.create(&quot;svg&quot;)
      .attr(&quot;viewBox&quot;, [-margin.left, -margin.top, width, dx])
      .style(&quot;font&quot;, &quot;10px sans-serif&quot;)
      .style(&quot;user-select&quot;, &quot;none&quot;);

    const gLink = svg.append(&quot;g&quot;)
      .attr(&quot;fill&quot;, &quot;none&quot;)
      .attr(&quot;stroke&quot;, &quot;#555&quot;)
      .attr(&quot;stroke-opacity&quot;, 0.4)
      .attr(&quot;stroke-width&quot;, 1.5);

    const gNode = svg.append(&quot;g&quot;)
      .attr(&quot;cursor&quot;, &quot;pointer&quot;)
      .attr(&quot;pointer-events&quot;, &quot;all&quot;);

    function update(source) {
      const duration = d3.event &amp;&amp; d3.event.altKey ? 2500 : 250;
      const nodes = root.descendants().reverse();
      const links = root.links();

      tree(root);

      let left = root;
      let right = root;
      root.eachBefore(node =&gt; {
        if (node.x &lt; left.x) left = node;
        if (node.x &gt; right.x) right = node;
      });

      const height = right.x - left.x + margin.top + margin.bottom;

  const transition = svg.transition()
      .duration(duration)
      .attr(&quot;viewBox&quot;, [-margin.left, left.x - margin.top, width, height])
      .tween(&quot;resize&quot;, window.ResizeObserver ? null : () =&gt; () =&gt; svg.dispatch(&quot;toggle&quot;));

  const node = gNode.selectAll(&quot;g&quot;)
    .data(nodes, d =&gt; d.id);

  const nodeEnter = node.enter().append(&quot;g&quot;)
      .attr(&quot;transform&quot;, d =&gt; `translate(${source.y0},${source.x0})`)
      .attr(&quot;fill-opacity&quot;, 0)
      .attr(&quot;stroke-opacity&quot;, 0)
      .on(&quot;click&quot;, (event, d) =&gt; {
        d.children = d.children ? null : d._children;
        update(d);
      });

 nodeEnter.on(&quot;click&quot;, (event, d) =&gt; {
  d.children = d.children ? null : d._children;
  update(d);
  d3.select(&quot;#node-info&quot;).text(d.data.name);
});
      
  nodeEnter.append(&quot;circle&quot;)
      .attr(&quot;r&quot;, 2.5)
      .attr(&quot;fill&quot;, d =&gt; d._children ? &quot;#555&quot; : &quot;#999&quot;)
      .attr(&quot;stroke-width&quot;, 10);

  nodeEnter.append(&quot;text&quot;)
      .attr(&quot;dy&quot;, &quot;0.31em&quot;)
      .attr(&quot;x&quot;, d =&gt; d._children ? -6 : 6)
      .attr(&quot;text-anchor&quot;, d =&gt; d._children ? &quot;end&quot; : &quot;start&quot;)
      .text(d =&gt; d.data.name)
    .clone(true).lower()
      .attr(&quot;stroke-linejoin&quot;, &quot;round&quot;)
      .attr(&quot;stroke-width&quot;, 3)
      .attr(&quot;stroke&quot;, &quot;white&quot;);

  const nodeUpdate = node.merge(nodeEnter).transition(transition)
      .attr(&quot;transform&quot;, d =&gt; `translate(${d.y},${d.x})`)
      .attr(&quot;fill-opacity&quot;, 1)
      .attr(&quot;stroke-opacity&quot;, 1);

  const nodeExit = node.exit().transition(transition).remove()
      .attr(&quot;transform&quot;, d =&gt; `translate(${source.y},${source.x})`)
      .attr(&quot;fill-opacity&quot;, 0)
      .attr(&quot;stroke-opacity&quot;, 0);

  const link = gLink.selectAll(&quot;path&quot;)
    .data(links, d =&gt; d.target.id);

  const linkEnter = link.enter().append(&quot;path&quot;)
      .attr(&quot;d&quot;, d =&gt; {
        const o = {x: source.x0, y: source.y0};
        return diagonal({source: o, target: o});
      });

  link.merge(linkEnter).transition(transition)
      .attr(&quot;d&quot;, diagonal);

  link.exit().transition(transition).remove()
      .attr(&quot;d&quot;, d =&gt; {
        const o = {x: source.x, y: source.y};
        return diagonal({source: o, target: o});
      });

  root.eachBefore(d =&gt; {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}

update(root);

document.body.appendChild(svg.node());

<!-- language: lang-css -->

.text{
  min-height:70px;
}

<!-- language: lang-html -->

&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.4/d3.min.js&quot;&gt;&lt;/script&gt;
&lt;div class=&quot;text&quot;&gt;
 &lt;p&gt;Clicked node text:&lt;/p&gt;
 &lt;p id=&quot;node-info&quot;&gt;&lt;/p&gt;
&lt;/div&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月4日 08:04:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75924563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定