我正在尝试运行 Mike Bostock 的 Zoomable Circle Paking example在我的页面上,但我遇到了问题。
我已将代码封装在一个闭包中,因为我在单个页面上有多个可视化效果。就像这样:
<script>
(function(){
//zoomable circle packing code here ...
})(window,d3);
</script>
可视化加载正常,但当我单击任何圆圈或区域时,出现以下错误:“(index):2444 Uncaught TypeError: Cannot read property 'parent' of undefined”
似乎指向该行:
transition.selectAll("text")
.filter(function(d) { return d.parent === focus || this.style.display === "inline"; })
...
无法理解为什么找不到父节点。
最佳答案
修复了需要在 javascript 闭包内使用循环打包可视化的情况。出现此问题的原因是,父级有时可能为空值,因为可视化项未附加到 html 页面的 #body 中。
因此您需要处理文本翻译部分内的情况:
transition.selectAll("text")
.filter(function(d) { return d.parent === focus || this.style.display === "inline"; })
.style("fill-opacity", function(d) { return d.parent === focus ? 1 : 0; })
.each("start", function(d) { if (d.parent === focus) this.style.display = "inline"; })
.each("end", function(d) { if (d.parent !== focus) this.style.display = "none"; });
相反,您可以处理空值情况:
transition.selectAll("text")
.filter(function(d) {
if(!(d === undefined))
{
return d.parent === focus || this.style.display === "inline";
}
})
.style("fill-opacity", function(d) {
if(!(d === undefined))
{
return d.parent === focus ? 1 : 0;
}
})
.each("start", function(d) {
if(!(d === undefined))
{
if (d.parent === focus) this.style.display = "inline";
}
})
.each("end", function(d) {
if(!(d === undefined))
{
if (d.parent !== focus) this.style.display = "none";
}
});
这应该可以正常工作,没有任何问题。
关于javascript - 可缩放圆形包装 - 父级未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38280773/