我正在学习 D3,并尝试通过将鼠标悬停在 SVG 圆圈上来在散点图上显示数据信息。我从 csv 文件中获取数据(数据位于太阳系,包含行星名称、质量和半径)并且所有圆圈都正确显示,但是当我尝试在鼠标悬停时 console.log 数据信息(例如质量)它不记录任何内容。鼠标悬停操作运行正常,但控制台告诉我请求的值是“未定义”。我哪里搞砸了?这是我的代码:
<!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>
Run Code Online (Sandbox Code Playgroud)
Mic*_*sky 13
从 D3 V6开始,所有鼠标事件处理程序都将事件作为第一个参数传递,将数据作为第二个参数传递。在V5或更早版本中,您的代码将可以运行。
V6 或更高版本:
.on('mouseover', (event, d) => console.log(d.mass));
Run Code Online (Sandbox Code Playgroud)
V5 或更早版本:
.on('mouseover', d => console.log(d.mass));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4308 次 |
| 最近记录: |