2013-03-20 88 views
9

我想製作一個氣泡圖,如果我點擊一個氣泡,氣泡的標題應該出現在控制檯中。我嘗試了一些方法,但沒有成功。D3.js,需要單擊事件在d3.js

d3.json("deaths.json", 
function (jsondata) { 

    var deaths = jsondata.map(function(d) { return d.deaths; }); 
var infections = jsondata.map(function(d) { return d.infections; }); 
var country = jsondata.map(function(d) { return d.country; }); 
var death_rate = jsondata.map(function(d) { return d.death_rate; }); 

    console.log(deaths); 
console.log(death_rate); 
console.log(infections); 
console.log(country); 
console.log(date); 

//Making chart 

for (var i=0;i<11;i++) 
{ 
var f; 
var countryname=new Array(); 
var dot = new Array(); 
dot = svg.append("g").append("circle").attr("class", "dot").attr("id",i) 
.style("fill", function(d) { return colorScale(death_rate[i]); }).call(position);  

//adding mouse listeners.... 

dot.on("click", click()); 
function click() 
{ 
    /***********************/ 
console.log(country); //i need the title of the circle to be printed 
    /*******************/ 
    } 

function position(dot) 
{ 
dot .attr("cx", function(d) { return xScale(deaths[i]); }) 
    .attr("cy", function(d) { return yScale(death_rate[i]); }) 
    .attr("r", function(d) { return radiusScale(infections[i]); }); 
dot.append("title").text(country[i]); 
} 
} 
}); 

我需要打印的圓圈標題 請幫忙!!!

回答

21

您使用on("click", ...)功能有了好主意。不過,我看到兩件事:

  • 第一個問題是,您不要在click事件上調用函數,而是調用它的值。所以,你寫dot.on("click", click());而不是dot.on("click", click);。爲了理解這種差異,我們假設函數的點擊需要一個參數,例如代表有趣的點,它會是什麼?那麼,你會寫:

    dot.on("click", function(d){click(d)}) 
    

    即相當於(且不易出錯)寫作:

    dot.on("click", click) 
    
  • 現在,第二點是,你確實想通過節點作爲函數click的參數。幸運的是,在我的示例中使用on事件時,函數click被調用,參數d表示dot的數據。因此,你現在可以這樣寫:

    dot.on("click", click); 
    function click(d) 
    { 
        console.log(d.title); //considering dot has a title attribute 
    } 
    

    注意:您還可以通過與i代表數組中的索引寫function click(d,i)使用另一種說法,看documentation瞭解更多詳情。

0

如果您對您的數據的標題,

dot.on('click' , function(d){ console.log(d.title); });