在 d3js tree sample ,我尝试将 update 调用移到 d3.json 函数之外。当我这样做时,我得到:
TypeError: d is undefined
这是代码(这里的函数与示例的链接略有不同)。请注意,我将对 update 的调用移至 d3.json 函数之外。请注意,root 是一个全局变量。
d3.json("../data/flare.json", function(json) {
root = json;
root.x0 = height / 2;
root.y0 = 0;
function collapse(d) {
if (d.children) {
d._children = d.children;
d._children.forEach(collapse);
d.children = null;
}
}
root.children.forEach(collapse);
// move this out
// update(root);
});
update(root);
function update(source) {.....
最佳答案
d3.json
是异步调用。这意味着调用将立即返回,但处理程序中的代码要稍后才会运行。就您而言,这意味着当您调用 update(root)
时,root
未定义(或为空)。
简而言之,您必须从d3.json
的回调内部调用update(root)
。虽然有一些可能性可以使其在回调之外工作,但这些可能性要复杂得多。
关于javascript - d3js 树的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20902524/