You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在D3可折叠树中仅为非空LINE2节点添加文本元素?

D3可折叠树:仅为LINE2非空节点添加第二行文本

要实现仅当d.LINE2不为空时才添加第二行文本元素,你可以利用D3的filter方法先筛选出符合条件的节点,再为这些节点创建文本元素,避免生成多余的DOM节点。

修改后的代码如下:

nodeEnter.filter(function(d) {
  // 过滤出LINE2不为null、undefined且非空字符串的节点
  return d.LINE2 != null && d.LINE2.trim() !== '';
})
.append("text")
.attr("x", function(d) { return d.children || d._children ? -13 : 13; })
.attr("dy", "3.6em")
.attr("fill", "#777")
.style("font-size", "10px")
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.text(function(d) { return d.LINE2; })
.style("fill-opacity", 1)
.style("fill", "blue");

说明

  • filter方法会遍历选择集中的每个节点,仅保留返回值为true的节点,这样后续的append操作只会作用在LINE2有效的节点上。
  • 判断条件d.LINE2 != null可以同时排除null和undefined,加上trim() !== ''则排除空字符串或仅含空白字符的情况,确保只处理真正有内容的LINE2字段。

内容的提问来源于stack exchange,提问作者user1009073

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 01:15:31