如何按类选择元素并在 D3 中检索其 ID

How to Select Element by Class and Retrieve its ID in D3

本文关键字:检索 ID D3 何按类 选择 元素      更新时间:2023-09-26

请考虑以下代码:

   d3.selectAll("#treemap rect").on("click", function(){
      msa = d3.select(this).attr('id');
      console.log(msa);
    });

.HTML:

<div id="treemap" ...>
    <rect class="node" id="cityName" ...>
    <rect class="node" id="cityName" ...>
    <rect class="node" id="cityName" ...>
    ...
</div>

此外,下面是创建树状图结构的代码:

var node = div.datum(newRoot[0]).selectAll(".node")
          .data(treemap.nodes)
          .enter().append("rect")
            .attr("class", "node")
            .attr("id", function(d){
              return d.cityname ? d.cityname.replace(/['W's]/g,"")+"-"+d.stusps: null;
            })...//The rest is inconsequential for this problem.

现在msa = d3.select(this).attr('class');返回预期的"节点"。但是,该元素上的 ID 是一个城市的名称,上面的 JavaScript 代码返回 null,我可以看到 ID 在 DOM 中。为什么.attr()方法不接受"id"和"class",我如何获得ID?

此外,我可以在我的堆栈中使用另一个库(如 JQuery)来获取 ID,但我想使用 D3 来做到这一点。这可能是我内心的纯粹主义者;)

我看了这里,仍然没有看到它。有什么想法,谢谢?

更新:

一个建议是将 SVG 附加到div,然后像这样创建树形图,如下所示:

   var div = d3.select("#dashboardA").append("div")
      .style("position", "relative")
      .attr("id", "treemap");
div = div.append("svg")
  .style("width", (width + margin.left + margin.right) + "px") //1220px
  .style("height", (height + margin.top + margin.bottom) + "px") //558px
  .style("margin", "auto")
  .style("left", margin.left + "px")
  .style("top", margin.top + "px");

结果:

树状图现在不可见或无法访问。此外,我发现的大多数树形图示例都创建没有任何 SVG 标签的树状图。这是一个官方示例。他们都错了吗?

您的标记无效。 您不能在 HTML divrect SVG ;矩形需要嵌套在 SVG 容器中。

之后,使用此代码:

d3.selectAll("#treemap rect").on("click", function(){
  msa = d3.select(this).attr('id');
  console.log(msa);
});

你在点击什么? 无效标记不会产生任何矩形,也不会单击任何内容。

所以。。。如果将矩形放置在svg则代码按预期工作。