How to make labels and nodes in D3 forced layout clickable to navigate to a URL?

前端 未结 2 546
一向
一向 2021-01-13 16:31

I am using a force based layout using D3 and was wondering if it\'s possible that when I click either the nodes or the labels, I am automatically taken to the url stored in

相关标签:
2条回答
  • 2021-01-13 17:00

    Generally speaking, you can add click events to SVG elements in D3.js using

    .on('click', function(d, i) {
      window.location.href = d.url;
    })
    

    d is the data object and the i is in the index of d within the collection.

    Just add that click handler to your text node as well as your node (path) node like in this fiddle http://jsfiddle.net/jNyrf/

    0 讨论(0)
  • 2021-01-13 17:03

    You have two options here.

    • You can use the .on("click", ...) handler to set the current page to the target.
    • You can use an a element with .attr("xlink:href", url) that contains the element acting as a hyperlink to set the link in a more traditional way.

    More information in this question/answer, although I believe you don't have to import the xlink namespace explicitly, at least not in the latest version of D3.

    0 讨论(0)
提交回复
热议问题