无法使D3 .on('mouseover',...)正常工作 [英] Cannot get D3 .on('mouseover', ...) to work

查看:71
本文介绍了无法使D3 .on('mouseover',...)正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习D3,并且试图通过将鼠标悬停在SVG圈子上来在散点图上显示数据信息.我从csv文件中获取数据(数据位于太阳系中,并带有行星名称,质量和半径),并且所有圆都正确显示,但是当我尝试进行控制台操作时,将鼠标悬停时记录数据信息(例如质量)它不会记录任何内容.鼠标悬停动作工作正常,但是控制台告诉我所请求的值是未定义".我在哪里弄糟?这是我的代码:

I'm learning D3 and I'm trying to display data infomation on a scatterplot by hovering on the SVG circles. I take the data from a csv file (data is on the Solar System, with planet names, masses and radiuses) and all the circles show up correctly but when I try to console.log the data information (for instance the mass) on mouseover it does not log anything. The mouseover action is functioning OK but the console tells me that the value requested is "undefined". Where did I mess up? This is my code:

<!DOCTYPE html>
<html lang="en">
<head>

    <style type="text/css">
    body{
        background-color: black;
    }
    #chart{
        background-color: black;
        width: 800px;
        height: 500px;
        border: solid 1px white;
    }
    svg{
        background-color: white;
    }
    .dot{
        stroke: red;
        stroke-width: 1px;
    }
    </style>
    
    <script type="text/javascript" src="https://d3js.org/d3.v6.min.js"></script>
</head>

<body>

    <div id="chart"></div>

    <script type="text/javascript">
        var width = 800;
        var height = 500;
        var circles;
        var svg = d3.select('#chart')
                .append('svg')
                .attr('width', width + 'px')
                .attr('height', height + 'px');

        d3.csv('astro.csv').then(function(data){

            xScale = d3.scaleLinear()
                .domain([0,500])
                .range([0, 800]);

            circles = svg.selectAll('.dot')
                .data(data)
                .enter()   
                .append('circle')
                .attr('class', '.dot')
                .attr('cx', function(d){
                    return xScale(d.mass);
                })
                .attr('cy', 100)
                .attr('r', 20)
                .on('mouseover', function(d){
                    console.log(d.mass);
                })                
        });
    </script>
</body>
</html>

推荐答案

自D3 V6 起,所有鼠标事件处理程序都将一个事件作为第一个参数传递,将数据作为第二个参数传递.在 V5 或更早的版本中,您的代码将可用.

Since D3 V6, all mouse event handlers has an event passed as the first argument and data as the second. In the V5 or earlier, your code will work.

V6或更高版本:

.on('mouseover', (event, d) => console.log(d.mass));

V5或更早版本:

.on('mouseover', d => console.log(d.mass));

这篇关于无法使D3 .on('mouseover',...)正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆