2013-05-07 117 views
0

我想在鼠標懸停上顯示文字。D3在鼠標懸停時追加文字時遇到問題

var circle = elemEnter.append("circle") 
      .attr("r", function(d){return d.r*2}) 
      .attr("dx", function(d){return d.x}) 
      .attr("stroke","gray") 
      .attr("fill", "#91c6ed") 
      .on("mouseover", function() 
          {d3.select(this).style("stroke", "#ff7f0e"); 
       d3.select(this).style("stroke-width", "2px"); 
       elemEnter.append("text") 
         .text(function(d){return d.name})}) 
      .on("mouseout", function() 
          {d3.select(this).style("stroke", "gray"); 
          d3.select(this).style("stroke-width", "1px");}); 

這段代碼的作品,但顯示在所有的圈子所有的名字,當我試圖取代

elemEnter.append(「文本」)。文本(函數(d){回報d.name})

通過

d3.select(本).append( 「文本」)。文本(d.name)

沒有任何反應。

我認爲這是可能的,但我不知道我做錯了什麼。

+1

你想要提示嗎? [這個答案](http://stackoverflow.com/questions/10805184/d3-show-data-on-mouseover-of-circle/10806220#10806220)應該有所幫助。 – 2013-05-07 17:02:14

+0

爲什麼你不使用第二個例子中的函數? '.text(func ...)' – cmonkey 2013-05-07 17:10:19

回答

2

您不能將文本附加到圓圈。您需要以g開頭,然後將圓圈追加到g並將文本追加到g。請記住,其G不會有CX/CY屬性,因此你需要將數據放到下面的語法:

.attr("transform", function (d) {return "translate("+d.X+","+d.Y")"}) 

如果你綁定的數據,將其綁定到G,然後按剛裸體將圓圈和文字附加到g。