3

该实验基于“国家健康与财富”示例。当鼠标悬停在每个点上时,我试图显示一个工具提示样式的标签并漂浮在每个点上方。每个数据元素都有一个名为“名称”的属性,我想在工具提示中显示它。为了简洁起见,我省略了大部分不相关的代码。

// Create all the dots, one for each data point.
var dot = svg.append("g")
    .attr("class", "dots")
  .selectAll(".dot")
    .data(myData)
  .enter().append("circle")
    .attr("class", "dot")
    .call(position)
    .call(enableInteraction)
    .sort(order);

// Create a tooltip element.
var tooltip = svg.append("text")
    .attr("class", "tooltip");

// Assign each of the dots the various mouse events.
function enableInteraction(dot) {
  dot.on("mouseover", mouseover)
     .on("mouseout", mouseout)
     .on("mousemove", mousemove);

  function mouseover() {
    tooltip.text(???); // How do I get the name into here?
  }

  function mouseout() {
    tooltip.text("");
  }

  function mousemove() {
    var cursor = d3.mouse(this);
    tooltip.attr("x", cursor[0] + 5)
           .attr("y", cursor[1] + 5);
  }
}

我尝试使用一个函数来检索名称并将其传递给 enableInteraction(),如下所示:

.call(enableInteraction, function(d) { return d.name; } )

但是传递的是函数对象而不是它的返回值。

那么如何让每个数据元素的名称显示在工具提示中呢?

4

1 回答 1

2

您可以使用柯里化技术将该信息放入您的鼠标悬停事件处理程序中。我不确定获取名称的语法,但这是我的想法:

// this function returns a function
function moveoverHandler(dot) {
    return function mouseover() {

        // I'm not sure if this is how you get the "name" property from the "dot" object 
        // Please update this as needed
        var name = dot.data("name");  

        tooltip.text(name);  
    }
}

然后像这样连接处理程序:

dot.on("mouseover", mouseover(dot));
于 2012-08-03T00:20:44.717 回答