简体   繁体   中英

Adding Links to Nodes in D3

So I'm dealing with a problem in my d3 visual in which I'm trying to create nodes which have clickable links to them. I'm just learning d3 so I was having trouble creating these links. Now so far i've gotten links on all the nodes but I want to achieve essentially is to have different links for each node. Currently I just put in a url for every single node but how would i select an individual node and attach a link to it. I want to have it so when a user clicks the object node it goes to another page.

var onode = svg.append('g').selectAll(".outer_node")
        .data(data.outer)
      .enter().append("g")
        .attr("class", "outer_node")
        .on("mouseover", mouseover)
        .on("mouseout", mouseout)
        .on("click", click);

function click (d){
    window.open("https://www.google.com", "_self");
    }

This makes it so each node has the same exact link, i didn't know exactly how to assign different links. Can someone please help?

Assuming you have URLs stored in the dataset, the you can access the URL in your function:

function click (d){
    let url = "http://" + d.url; //or whatever your URL field is called in the data
    window.open(url, "_self");
}

You mention "position in the array", so if the URLs are in separate array, but which align with the dataset, then you could use

function click (d, i){ //is this 0 based index of each item in the selection
    let url = urlData[i]
    window.open(url, "_self");
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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