D3.js,需要在d3.js中点击事件

Pha*_*dar 9 javascript 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]);
}
}
});
Run Code Online (Sandbox Code Playgroud)

我需要要打印的圆圈标题请帮忙!!!

Chr*_*che 21

通过使用该on("click", ...)功能,您有了一个好主意.但是我看到两件事:

  • 第一个问题是您不会在click事件上调用该函数,而是调用其值.所以,你写dot.on("click", click());而不是dot.on("click", click);.为了理解差异,让我们假设函数click需要一个参数,例如代表有趣的点,它会是什么?好吧,你会写下面的内容:

    dot.on("click", function(d){click(d)}) 
    
    Run Code Online (Sandbox Code Playgroud)

    这与写作相同(并且不易出错):

    dot.on("click", click)
    
    Run Code Online (Sandbox Code Playgroud)
  • 现在,第二点是,确实你想要将节点作为函数的参数传递click.幸运的是,on正如我在我的示例中所使用的那样,使用d表示数据的参数调用函数click dot.因此你现在可以写:

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

    注意:您还可以通过写入function click(d,i)i在数组中表示索引来使用另一个参数,请参阅文档以获取更多详细信息.