首页 > 解决方案 > D3强制有向图点击事件不起作用

问题描述

我也是 d3.js 和 JavaScript 的新手。这是我在 d3 中使用 CSV 文件数据的强制定向图的代码。

在开始之前,这是我想要制作类似http://bl.ocks.org/eesur/be2abfb3155a38be4de4的代码片段

关于图表的一切都很好,但 onclick 事件似乎不起作用。单击功能应该将单击事件应用于 csv 数据中的所有节点(即 16 个节点),但我的图表只有 9 个节点。

我试图将点击数据放到这些特定节点,但失败了。这也是我要绘制图表的 CSV 数据

https://github.com/hohadang1999/Authorship-Network-Graph/blob/master/publications.csv

    d3.csv("publications.csv", function(error, links) {
var nodes = {};
links.forEach(function(link) {
    link.source = nodes[link.source] || 
        (nodes[link.source] = {name: link.source}); 
    link.target = nodes[link.target] || 
        (nodes[link.target] = {name: link.target});    

});
var width = 1500,
    height = 500;


var force = d3.layout.force()
    .nodes(d3.values(nodes))
    .links(links)
    .size([width, height])
    .linkDistance(180)
    .charge(-300)
    .on("tick", tick)
    .start();

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("svg:defs").selectAll("marker")
    .data(["end"])      
  .enter().append("svg:marker")    
    .attr("id", String)
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", -1.5)
    .attr("markerWidth", 6)
    .attr("markerHeight", 6)
    .attr("orient", "auto")
  .append("svg:path")
    .attr("d", "M0,-5L10,0L0,5");

var path = svg.append("svg:g").selectAll("path")
    .data(force.links())
  .enter().append("svg:path")
    .attr("class", "link")
    .attr("marker-end", "url(#end)")
    .style("stroke","#eee")
    .on("click", click);

var node = svg.selectAll(".node")
    .data(force.nodes())
  .enter().append("g")
    .attr("class", "node")
    .on("click", click)
    .call(force.drag);


node.append("circle")
    .attr("r", 15)
    .style("fill","lightcoral")
    .style("stroke","red");


node.append("text")
    .attr("x",20)
    .attr("dy", ".65em")
    .text(function(d) { return d.name; });


node.on("click", function )




function tick() {
    path.attr("d", function(d) {
        var dx = d.target.x - d.source.x,
            dy = d.target.y - d.source.y,
            dr = Math.sqrt(dx * dx + dy * dy);
        return "M" + 
            d.source.x + "," + 
            d.source.y + "A" + 
            dr + "," + dr + " 0 0,1 " + 
            d.target.x + "," + 
            d.target.y;
    });
    node
        .attr("transform", function(d) { 
   return "translate(" + d.x + "," + d.y + ")"; });
}
function click() {
    d3.select(this).select("circle").transition()
        .duration(750)
        .attr("r",6)
        .style("fill", "#ccc");


}



});

我想要实现的是这些节点上的点击事件,如图所示

标签: javascriptd3.jsonclickd3-force-directed

解决方案


可能还有其他问题(我没有运行您的脚本),但我可以清楚地看到一个问题"node.on("click", function )是没有将点击事件映射到click()您编写的函数的行。您应该将其更改为node.on("click", click).


推荐阅读