简体   繁体   English

如何在D3.js中创建轴刻度标签超链接

[英]How to make axis tick labels hyperlinks in D3.js

In D3.js, how do I assign HTML elements/attributes to tick labels? 在D3.js中,如何将HTML元素/属性分配给刻度标签? I'm specifically interested in making them hyperlinks, but it could be generalized to making them images, or something strange like alternating div classes. 我特别感兴趣的是使它们成为超链接,但它可以概括为使它们成为图像,或者像交替的div类那样奇怪。

var data = [{"count": 3125,"name": "aaa"}, {"count": 3004,"name": "bbb"}...

y = d3.scale.ordinal()
    .rangeRoundBands([0, height], 0.1)
    .domain(data.map(function (d) {
      return d.name;
    }))

yAxis = d3.svg.axis().scale(y)
vis.append("g")
   .attr("class", "y axis")
   .call(yAxis)

http://jsfiddle.net/SFDrv/ http://jsfiddle.net/SFDrv/

So in the JSfiddle, how would I link to www.example.com/aaa, www.example.com/bbb, www.example.com/ccc, etc? 那么在JSfiddle中,我如何链接到www.example.com/aaa,www.example.com/bbb,www.example.com/ccc等?

For the JSfiddle you posted, you can create a selection of all text that are strings (these are the y-axis ticks), and then use .on("click", function) , to link each label. 对于您发布的JSfiddle,您可以创建所有字符串text的选择(这些是y轴刻度),然后使用.on("click", function)链接每个标签。 Here's a working example: 这是一个有效的例子:

d3.selectAll("text")
    .filter(function(d){ return typeof(d) == "string"; })
    .style("cursor", "pointer")
    .on("click", function(d){
        document.location.href = "http://www.example.com/" + d;
    });

I forked your JSFiddle and have the whole example there: http://jsfiddle.net/mdml/Qm9U7/ . 我分叉你的JSFiddle并在那里有完整的例子: http//jsfiddle.net/mdml/Qm9U7/

A better solution would be to have an array of y-axis values and to use those to filter the text elements in the document, instead of testing whether each text element's data is a string. 更好的解决方案是获得一组y轴值并使用它们来过滤文档中的text元素,而不是测试每个text元素的数据是否为字符串。 The best way to do that depends on the rest of the code, however, so it may differ from application to application. 然而,最好的方法取决于代码的其余部分,因此它可能因应用程序而异。

To create axis with images you need to create them yourself and not use the d3.svg.axis() . 要使用图像创建轴,您需要自己创建它们而不使用d3.svg.axis() This creates floated li tags with certain width... 这会创建具有一定宽度的浮动li标签......

// generate axis
x = d3.scale.linear().range([min, max]).domain([minValue, maxScaleValue]);
xAxis = d3.scale.identity().domain([minValue, maxScaleValue]);
var ticks = xAxis.ticks(10);
if (ticks.length) {
    var tickDiff = Math.abs(ticks[1] - ticks[0]);
    scope.legend
        .selectAll('li')
        .data(ticks)
        .enter()
        .append('li')
        .text(xAxis)
        .style('width', x(tickDiff));
}
scope.legend
    .selectAll("li")
    .data(ticks)
    .exit()
    .remove();

Also there is useful article about d3 axis that helped me a lot. 还有关于d3轴的有用文章对我帮助很大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM