如何按类选择元素并在 D3 中检索其 ID
How to Select Element by Class and Retrieve its ID in D3
请考虑以下代码:
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 div
中rect
SVG ;矩形需要嵌套在 SVG 容器中。
之后,使用此代码:
d3.selectAll("#treemap rect").on("click", function(){
msa = d3.select(this).attr('id');
console.log(msa);
});
你在点击什么? 无效标记不会产生任何矩形,也不会单击任何内容。
所以。。。如果将矩形放置在svg
则代码按预期工作。
相关文章:
- MongoDB 2.0.0 驱动程序,按 ID 检索记录时出现问题
- 如何从链接中检索 ID
- 在按键时检索文本区域的 ID
- 正在根据ID从数组中检索对象
- 如何使用地点ID从Google Places JS API检索地点详细信息
- Javascript REGEX:需要从嵌入URL中检索ID以及开始和结束时间
- 如何在没有任何元素id的情况下检索表中的文本内容
- 创建一个bookmarklet,可以检索文本框的所有最大长度,然后在表中打印id和最大长度
- 如何将下拉列表中检索到的值的id从数据库发送到php文件
- Ajax - 在“成功”之后转到另一个页面,从那里的URL中检索用户ID
- 将 ID 添加到画布绘图以供以后检索
- Angular JS:根据 id 检索 json 数据
- 从 javascript 中的 URL 检索 ID 参数
- 如何通过单击并检索id来检索值
- 用javascript从cell中检索id
- Jquery插件在函数原型中检索id
- 我需要我的javascript代码来按代码块检索id
- 按文本搜索并检索id
- 使用javascript从引导程序表中检索id
- 如何使用“this”从选定项目检索id