问题
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