Adding clickable links or onClick handler in a D3 force directed diagram?

别等时光非礼了梦想. 提交于 2020-01-25 00:12:05

问题


When a user clicks on a node in a D3 force directed diagram, is it possible to send them to a URL or to call JavaScript such as alert("You clicked on node 1")?


回答1:


A click listener can be applied to a selection. Therefore you can apply it to the nodes by calling an .on("click",function(d){...}) on your nodes selection. This is not in any kind special for the force layout.

Most of the time force layouts are combined with a drag behavior. You should be aware that the click is also triggered after a drag on the node ends.

If you take this example of a fore directed diagram, you could use the node selection and change it to this:

var node = svg.selectAll(".node")
    .data(graph.nodes)
  .enter().append("circle")
    .attr("class", "node")
    .attr("r", 5)
    .style("fill", function(d) { return color(d.group); })
    .on("click", function(d){
      console.log(d);
      alert("You clicked on node " + d.name);
    });
    //.call(force.drag);

You can leave the .call(force.drag) added if you want the click and drag behavior combined.



来源:https://stackoverflow.com/questions/30690732/adding-clickable-links-or-onclick-handler-in-a-d3-force-directed-diagram

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!