D3.js热力图Tooltip显示undefined值及控制台警告问题排查求助
问题分析与解决方案
嘿,我来帮你搞定这两个问题!先从最影响功能的Tooltip值错误说起,再聊聊那个控制台警告。
1. Tooltip显示undefined的原因与修复
你用的是D3 v6,这个版本里事件处理函数的参数顺序发生了变化!在D3 v6及以后,事件处理函数的第一个参数不再是数据d,而是event对象,数据d变成了第二个参数。
看你原来的代码:
.on("mousemove", function(d){ tooltip.html("The exact value is: " + d.value) return tooltip.style("top", (d3.pointer(this)[1]) + "px").style("left",(d3.pointer(this)[0]+30) + "px"); })
这里的d其实是鼠标事件对象,不是你绑定的mapData.data里的数据,自然d.value就是undefined了。
修复后的代码:
把事件处理函数的参数改成(event, d),同时d3.pointer在v6里也可以直接用event作为参数,写法更简洁:
var tooltip = d3.select("#container") .append("div") .style("position", "absolute") .style("visibility", "hidden") .style("background", "#ffffff") svg.selectAll("rect") // 这里最好指定选择器,避免选择到其他无关元素 .data(mapData.data, function(d) {return d.group +':'+ d.variable;}) .enter() .append("rect") .attr("x", function(d) { return x(d.variable) }) .attr("y", function(d) { return y(d.group) }) .attr("width", x.bandwidth() ) .attr("height", y.bandwidth() ) .style("fill", function(d) { return colour(d.value)}) .on("mouseover", function(event, d){ return tooltip.style("visibility", "visible"); }) .on("mousemove", function(event, d){ tooltip.html("The exact value is: " + d.value) // 用d3.pointer直接从event获取鼠标位置 const [xPos, yPos] = d3.pointer(event); return tooltip.style("top", (yPos + 10) + "px").style("left",(xPos + 30) + "px"); }) .on("mouseleave", function(event, d){ return tooltip.style("visibility", "hidden"); })
2. 控制台警告"rbug/1173575, non-JS module files deprecated."
这个警告是Chrome浏览器的一个已知提示,原因是你直接用<script>引入了D3 v6的ES模块版本(d3.v6.js是ES模块),但没有声明type="module",浏览器现在对这种非模块方式加载ES模块文件有 deprecation 警告。
解决方法:
- 方法一:给
<script>标签添加type="module"属性,改用模块方式引入D3:
<script type="module"> import * as d3 from "https://cdn.skypack.dev/d3@6"; // 你的D3代码需要写在这个module脚本内部 </script>
- 方法二:引入D3的UMD兼容版本(无需模块声明),比如用压缩版的CDN链接:
<script src="https://d3js.org/d3.v6.min.js"></script>
这个警告其实不影响代码功能,只是浏览器提示你规范加载模块文件,选上面任意一种方法都可以消除它。
内容的提问来源于stack exchange,提问作者Ashur Ragna
相关产品推荐
相关产品推荐

