我想在我的 D3 图表的 x 轴上呈现 HTML。基本上,我希望轴上的每个标签都是指向数据中另一列的超链接。
我试过了
x.domain(data.map(function(d) { return "<a href=\"" + d.SiteUrl + "\">" + d.Name + "</a>"; }));
但它根本不起作用。我没有获得超链接,而是获得了实际的文本值:
<a href="http://example.com">Something</a>
我也试过添加
.tickFormat(function(d) { return "<a href=\"" + d.SiteUrl + "\">" + d.Name + "</a>"; })
在 x 轴上,以及将 .attr("x", ...)
更改为
.attr("x", function(d) { return "<a href=\"" + d.SiteUrl + "\">" + x(d.Name) + "</a>"; })
在图表本身上。
我错过了什么吗?
最佳答案
(基于 https://groups.google.com/d/msg/d3-js/zoUjrm75iCg/EJg0YhnTw3YJ )
诀窍是使用svg:foreignObject
(如@thatOneGuy 在评论中所述),然后您可以将任何HTML 放置在轴标签内。下面的 html
处的函数通过 data[i].name
传递,其中可以放置任意 HTML。
var height = 500;
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(0).tickPadding(0).tickFormat(function(d) {return '';});
var tx = -5;
var ty = 2;
var tw = 50;
var th = 10;
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("g")
.append("svg:foreignObject")
.attr("width",tw)
.attr("height",th)
.attr("x", tx)
.attr("y", ty)
.append("xhtml:div")
.attr("class", "my-x-axis-label")
.html(function(schema) {return schema;});
CSS:
div.my-x-axis-label {
font: 10px sans-serif;
}
关于javascript - 在 X 轴刻度上呈现 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37295720/