一旦我尝试从Force-Directed Graph Example修改json文件,它就会出现以下错误:
Uncaught TypeError: Cannot read property 'nodes' of undefined
SyntaxError: Unexpected token
代码:
<!DOCTYPE html>
<meta charset="UTF8">
<style>
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
fill: none;
stroke: #bbb;
}
</style>
<body>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var width = window.innerWidth,
height = window.innerHeight;
var color = d3.scale.category20();
var force = d3.layout.force()
.linkDistance(10)
.linkStrength(2)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("xPata.json", function(error, graph) {
var nodes = graph.nodes.slice(),
links = [],
bilinks = [];
graph.links.forEach(function(link) {
var s = nodes[link.source],
t = nodes[link.target],
i = {}; // intermediate node
nodes.push(i);
links.push({
source: s,
target: i
}, {
source: i,
target: t
});
bilinks.push([s, i, t]);
});
force
.nodes(nodes)
.links(links)
.start();
var link = svg.selectAll(".link")
.data(bilinks)
.enter().append("path")
.attr("class", "link");
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 5)
.style("fill", function(d) {
return color(d.group);
})
.call(force.drag);
node.append("title")
.text(function(d) {
return d.name;
});
force.on("tick", function() {
link.attr("d", function(d) {
return "M" + d[0].x + "," + d[0].y + "S" + d[1].x + "," + d[1].y + " " + d[2].x + "," + d[2].y;
});
node.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
});
});
</script>
</body>
</html>
JSON:
{
"nodes":[
{"name":"Myriel","group":1},
{"name":"Napoleon","group":1},
{"name":"Mlle.Baptistine","group":1},
{"name":"Mme.Magloire","group":1},
{"name":"CountessdeLo","group":1},
{"name":"Geborand","group":1},
{"name":"Geborand","group":1}
],
"links":[
{"source":1,"target":0,"value":8},
{"source":2,"target":0,"value":8},
{"source":3,"target":0,"value":10},
{"source":4,"target":3,"value":10},
{"source":5,"target":3,"value":10},
{"source":6,"target":2,"value":10},
{"source":7,"target":5,"value":10}
]
}
当我重命名json文件时,它加载得很好。到底是怎么回事?也发生在其他例子上。
答案 0 :(得分:0)
原来它与D3.js无关。我的网络服务器是导致问题的原因;它缓存了json文件。不解释错误,但确实解释了重命名修复。