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; })
但功能對象被傳遞,而不是它的返回值。
那麼如何讓每個數據元素的名稱顯示在工具提示中?