2014-02-07 39 views
0

我是d3.js的新手,我对语法感到困惑。将标签添加到/更新为d3.js图

我平时知道如何标签添加到图......而与此代码(我从D3.js Force Layout - showing only part of a graph采取)

我曾尝试各种解决方案[.append(“文本”),进入().append(“text”)....]但我一直没有成功。

这里就是我认为我必须要改变一些代码的一部分(和,下面的代码,你会发现整个事情gihub回购)

 this.link = this.link.data(this.force.links(), function (d) { 

      return d.source.id + "-" + d.target.id; 
     }); 

     this.link.enter().insert("line", ".node").attr("class", "link") 

      .style("opacity", 0) 
      .transition().duration(1000) 

      .style("opacity", 1); 

     this.link.exit() 
      .remove(); 



     this.node = this.node.data(this.force.nodes(), function (d) { 
      return d.id; 

     }); 

     if (this.node.enter().empty()==false ||this.node.exit().empty() == false) { 
      transition = true; 
     } 


     this.node.enter() 
      .append("circle") 
      .style("opacity", 1) 
      .attr("class", "node") 
      .style("fill", function (d) { 
       return d.color; 
      }) 
      .attr("r", 18) 
      /*.on('mouseover', this.mouseOver)*/ 
      .on('mousedown', this.mouseDown) 
      .on('mouseout', this.mouseOut) 
      .on("dragstart", this.dragStart) 
      .on("click", this.click) 
      .call(this.nodeDrag) 
      .transition().duration(1000) 
      .style("opacity", 1) 
      .each("end",function(){transition=false;}); 


     this.node.each(function(d) { 
      if (d.centerNode==false) { 
       this.setAttribute('r',12); 
      } else if (firstRound) { 
       this.setAttribute('r',30); 
       firstRound =false; 
      } 
     }); 





     this.node.exit().transition().duration(1000).style("opacity", 0) 
      .each("end",function(){transition=false;}) 
      .remove(); 

https://github.com/coulmont/pornograph

+1

你想追加标签到什么地方? 'node'? –

+0

是的!我想将标签附加到节点(无论是在节点的中心还是侧面) – user1788720

回答

1

要为一个.enter()选择附加多组元素,您需要多次访问它。分组元素通常是一个好主意。

var gs = this.node.enter().append("g"); 
gs.append("circle") 
     .style("opacity", 1) 
     .attr("class", "node") 
     .style("fill", function (d) { 
      return d.color; 
     }) // etc 
gs.append("text") 
    .style("text-anchor", "center") 
    .text(...); 
+0

谢谢...不工作...您认为我需要将“this.node”的每个实例替换为“ gs“? – user1788720

+1

是的,您的其他代码将不得不反映这种变化。简单地重新分配'this.node'可能会更容易。 –

+0

重新分配意味着这个? var this.node = this.node.enter()。append(“g”); – user1788720