jQuery 如何在 d3 javascript 中为 SVG 文本元素分配唯一 id
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19387898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to assign unique id to SVG text element in d3 javascript
提问by DeBraid
Making a bar graph in d3. I have 30+ bars, with 30+ corresponding labels on x-axis. I would like x-axis labels to be hidden when the page loads (this is working), AND APPEAR only if user cursors over the corresponding bar (svg rect object). To do this I am assigning an id to each rect and each text element. When user cursors over rect, text will appear for ONLY the selected (mouseover'd) rect.
在 d3 中制作条形图。我有 30 多个条形图,x 轴上有 30 多个相应的标签。我希望在页面加载时隐藏 x 轴标签(这是有效的),并且仅当用户光标悬停在相应的栏(svg rect 对象)上时才出现。为此,我为每个矩形和每个文本元素分配了一个 id。当用户光标悬停在 rect 上时,文本将仅显示所选(鼠标悬停)的 rect。
I can assign id to rects, but not for text. Code:
我可以将 id 分配给 rects,但不能分配给文本。代码:
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("id", function(d){
return d.slug; // slug = label downcased, this works
}); // each rect has unique id
However, similar code for my text element on x-axis doesn't assign an id?!
但是,我在 x 轴上的文本元素的类似代码没有分配 id?!
svg.append("g")
.call(xAxis)
.selectAll("text")
.attr("id", function (d){ // inspect text element shows no ID.
return d.slug; // text doesn't have any id
})
.style("text-anchor", "end")
.attr("opacity", 0.2);
How can I assign a unique id to my text elements in x-axis? Thank you!
如何为 x 轴中的文本元素分配唯一 ID?谢谢!
回答by Lars Kotthoff
The problem is that no data is bound to the x axis ticks and therefore d
is undefined -- you should actually get an error message when running your code.
问题是没有数据绑定到 x 轴刻度,因此d
是未定义的——您实际上应该在运行代码时收到一条错误消息。
In this particular case, you can use the index to get the relevant data item like so.
在这种特殊情况下,您可以像这样使用索引来获取相关数据项。
svg.append("g").call(xAxis)
.selectAll("text")
.attr("id", function(d, i) { return dataset[i].slug; });
Note that this will only work if the number of axis ticks is the same as the number of data items.
请注意,这仅在轴刻度数与数据项数相同时才有效。