gpt4 book ai didi

javascript - 将数据传递给 d3.js 中的 .call

转载 作者:行者123 更新时间:2023-11-29 14:59:50 24 4
gpt4 key购买 nike

本实验基于Health & Wealth of Nations例子。当鼠标悬停在每个点上时,我试图显示一个工具提示样式的标签并 float 在每个点上方。每个数据元素都有一个名为“name”的属性,我想在工具提示中显示它。为了简洁起见,我省略了大部分不相关的代码。

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

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

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

最佳答案

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

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

关于javascript - 将数据传递给 d3.js 中的 .call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11787254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com