我已应用clustered dendrogram来展示组织的结构。它运作良好。另外,我想添加节点文本的链接。
我已经为每个节点的json数组添加了“url”键
{
"name": "Institutes",
"children": [
{ "name": "Social", "url": "http://social.example.com/" },
{ "name": "Health", "url": "http://health.example.com/" },
{ "name": "Nature", "url": "http://nature.example.com/" },
{ "name": "Education", "url": "http://social.example.com/" }
]
}
有两个问题:
<a>
标记未包含所有<text>
元素。它显示为<a></a><text></text>
。我希望它是<a><text></text></a>
。
如何从json中读取url
密钥,以便将其添加为href
属性的值(请参阅注释//???
的行)?
d3.json("org_chart.json", function(error, root) {
var nodes = cluster.nodes(root),
links = cluster.links(nodes);
var link = svg.selectAll(".link")
.data(links)
.enter().append("path")
.attr("class", "link")
.attr("d", diagonal);
var node = svg.selectAll(".node")
.data(nodes)
.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) {
return "translate(" + d.y + "," + d.x + ")";
});
node.append("circle")
.attr("r", 5.1);
node.append("a")
.attr("href", "#") //???
.attr("target","_blank");
node.append("text")
.attr("dx", function(d) {
return d.children ? -9 : 8;
})
.attr("dy", 3)
.style("text-anchor", function(d) {
return d.children ? "end" : "start";
})
.text(function(d) {
return d.name;
});
});
还有一件事:
我试过了
node.append("a").attr("href", function (d) { return d.url;});
然后返回undefined
。我也试过
node.append("a").attr("href", "http://example.com");
虽然看起来像
<g class="node" transform="translate(0,428.74692874692875)">
<circle r="5.1"></circle>
<a href="http://example.com/" target="_blank">
<text dx="-9" dy="3" style="text-anchor: end;">
Education
</text>
</a>
</g>
点击它时,它不会打开http://example.com。
答案 0 :(得分:1)
当你使用selection.append(name)
时,它会返回一个包含附加元素的新选择,因此你可以直接对它进行另一个追加,如下所示:
node.append("a").append("text");
为了获得url
属性,您需要使用访问器函数,如下所示:
node.append("a").attr("href", function (d) {
return d.url;
});
修改强>
对于链接,您可能需要在html文件中导入xlink命名空间:
<html xmlns:xlink="http://www.w3.org/1999/xlink">
并使用命名空间:
.append("svg:a").attr("xlink:href", urlAccessor)