2012-08-02 83 views
3

本實驗基於Health & Wealth of Nations示例。當鼠標懸停在它們上方時,我試圖讓工具提示樣式的標籤出現並浮在每個點上方。每個數據元素都有一個名爲「name」的屬性,我想在工具提示中顯示。爲了簡潔起見,我省略了大部分不相關的代碼。將數據傳遞給d3.js中的.call

// 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; }) 

但功能對象被傳遞,而不是它的返回值。

那麼如何讓每個數據元素的名稱顯示在工具提示中?

回答

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));