【问题标题】:Show content from data in tooltip d3在工具提示 d3 中显示数据的内容
【发布时间】:2016-06-08 02:50:59
【问题描述】:

我正在关注this 示例,向我的圈子添加工具提示,显示在地图上。

var tooltip = d3.select("body")
    .append("div")
    .attr("id", "mytooltip")
    .style("position", "absolute")
    .style("z-index", "10")
    .style("visibility", "hidden")
    .text("a simple tooltip");

然后我得到了这个鼠标悬停

// callbackfunction preparing the data
// then

var feature = g.selectAll("circle")
    .data(data.features)
    .enter()
    .append("circle")
//...

feature.on("mouseover",function(d) { 
    d3.select(this)
    .transition()
    .ease("elastic")
    .duration(500)
    .attr('r', function (d){ 
              return (d.features.xy);
          })
    d3.select("#mytooltip")
    .style("visibility", "visible")
    .text(function(d) {
        console.log(d.features.xy)
        return (d.features.xy)
     })

这不会显示xy 的值。 console.log 的输出是:

TypeError: undefined is not an object (evalating 'd.xy')

问题显然是使用d3.select("#mytooltip") 语句我输入了var tooltip,而我的data.features... 没有绑定到该var tooltip。如何将圆圈绑定到鼠标悬停(在调用 d3.select 后在 var feature = g.selectAll("circle") 中创建?

【问题讨论】:

    标签: javascript d3.js mouseevent mouseover


    【解决方案1】:

    .data 函数需要一个数组,分布在多个元素中(“数据”是复数形式)。如果你想给单个元素(即你的tooltip)提供一个“数据片段”,你需要.datum函数:

    tooltip.datum(myData)
    

    或者,您可以这样做:

    tooltip.data([myData])
    

    在您的原始代码中,由于您没有 tooltip 变量(也没有 myData),您可以将其插入到 mouseover 事件中:

    (...)
     d3.select("#mytooltip")
       .datum(d)
       .style("visibility", "visible")
    (...)
    

    另一种选择:您可以直接绘制工具提示,无需绑定任何数据:

    d3.select("#mytooltip")
       .style("visibility", "visible")
       .text(d.features.xy);
    

    这里的d 仍然指的是你鼠标悬停的对象的数据,所以这应该也可以。

    【讨论】:

    • 对不起,我以.data(myData) 行作为起点:最后的编辑应该会让事情更清楚。这里的myData 实际上应该是d
    • 我仍然很难跟上。在变量tooltip声明 中我没有更改任何内容,而在d3.select("#mytooltip") 中我只是添加datum(d)?
    • 是的,就是这样。
    • 为什么在你的最后一个例子中我不需要function(d) {....? d3 知道从哪里获取数据?
    • .text() 可以采用要显示的字符串,也可以采用将数据转换为字符串的函数。当每个元素的字符串不同时,后者在大量选择中很有用,但这里只有一个元素,并且您知道需要打印什么字符串:它仅取决于您圈子的数据。此数据在feature.on("mouseover",function(d) { 行上的参数d 中获取。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多