如何为d3中的SVG文本元素分配唯一的ID [英] how to assign unique id to SVG text element in d3 javascript

查看:2261
本文介绍了如何为d3中的SVG文本元素分配唯一的ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在d3中创建条形图。我有30多个酒吧,在x轴上有30多个相应的标签。我想要在页面加载(这是工作)时隐藏x轴标签,并且仅当用户光标在相应的条(svg rect对象)上时才会出现。为此,我为每个rect和每个文本元素分配一个id。当用户光标超过rect时,文本将只显示选定的(鼠标悬停)矩形。

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.

我可以将id分配给rect,但不能分配给文本。代码:

I can assign id to rects, but not for text. Code:

      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

但是,类似的代码为我的文本元素x轴doesn' t分配一个ID?

However, similar code for my text element on x-axis doesn't assign an 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);

如何为x轴上的文本元素分配唯一的ID?谢谢!

How can I assign a unique id to my text elements in x-axis? Thank you!

推荐答案

问题是没有数据绑定到x轴刻度,因此 d

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.

在这种特殊情况下,您可以使用索引来获取相关数据项如此。

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; });

请注意,这只有在轴刻度数与的数据项。

这篇关于如何为d3中的SVG文本元素分配唯一的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆