繁体   English   中英

D3.js对象中的超链接,第2部分

[英]Hyperlinks in D3.js objects, part 2

我是D3的新手,但根据以下示例将Reingold-Tilford树放在一起: http : //bl.ocks.org/mbostock/4339184

我正在尝试将超链接添加到每个链结之一的子节点上-基本上,任何在其前面带有白色圆圈的节点。

我发现了有关如何添加超链接的有用说明-d3.js对象中的超链接 -但不幸的是,我只了解其中的一半。

作者写道:

这很容易,只需添加更多“键”:“值”对。 例:

        "children": [
        {
            "name": "Google",
            "size": 3938,
            "url":  "https://www.google.com"

        },
        {
            "name": "Bing",
            "size": 3938,
            "url":  "http://www.bing.com"

        }
    ]

我同意,这很容易-我已经做到了。 但是,在完成之后,如何将页面的代码更改为,正如另一篇文章中的助手所写的那样,“在d3绘图代码中,为每个数据元素附加节点,然后包装要成为的元素带有svg:a标签的可点击链接:”

nodeEnter.append("svg:a")
.attr("xlink:href", function(d){return d.url;})  // <-- reading the new "url" property .append("svg:rect")
.attr("y", -barHeight / 2)
.attr("height", barHeight)
.attr("width", barWidth)
.style("fill", color)
.on("click", click);  // <- remove this if you like

这是我不明白的。 有人可以解释一下如何修改此内容以使其与本示例中的文本保持一致吗-http: //bl.ocks.org/mbostock/4339184

先感谢您。

马特

首先,您需要检查要追加的节点是否有子节点,因此可以区分哪些将是链接,哪些将是文本。 完成后,您可以追加正确的元素。 因此,与其像现在那样仅添加文本元素,不如:

node.append("text")
    .attr("dx", function(d) { return d.children ? -8 : 8; })
    .attr("dy", 3)
    .attr("text-anchor", function(d) { return d.children ? "end" : "start"; })
    .text(function(d) { return d.name; });

遍历他们,确定谁有孩子,并相应地添加正确的元素,如下所示:

node.each(function(d){
    var thisNode = d3.select(this);
    if (!d.children) {
        thisNode.append("a")
            .attr("xlink:href", function(d) { return d.url; })
            .append("text")
                .attr("dx", 8)
                .attr("dy", 3)
                .attr("text-anchor", "start")
                .text(function(d) { return d.name; });
    } else {
        thisNode.append("text")
            .attr("dx", -8)
            .attr("dy", 3)
            .attr("text-anchor", "end")
            .text(function(d) { return d.name; });      
    }
});

现在,只有没有子节点的节点才会被超链接。 仅供参考:正如您所看到的,我遗漏了一些仅用于检查子项的冗余功能,因为到那时您已经知道该节点是否有任何功能,您将不再需要这些功能。

暂无
暂无

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

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