Javascript 未捕获类型错误:无法读取属性';重量';未定义的
我试图在D3中建立一个力定向图。这是它的代码- index.htmlJavascript 未捕获类型错误:无法读取属性';重量';未定义的,javascript,json,d3.js,Javascript,Json,D3.js,我试图在D3中建立一个力定向图。这是它的代码- index.html <!DOCTYPE html> <meta charset="utf-8"> <style> .node { stroke: #FFFF; stroke-width: 1.5px; } .link { stroke: #111; } </style> <body> <h1>Hello there</h1> <script
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.node {
stroke: #FFFF;
stroke-width: 1.5px;
}
.link {
stroke: #111;
}
</style>
<body>
<h1>Hello there</h1>
<script src="d3.v3.min.js"></script>
<script>
var width = 960,
height = 500;
var color = d3.scale.category20();
var force = d3.layout.force()
.charge(-120)
.linkDistance(30)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
d3.json("copy.json", function(error, graph) {
force
.nodes(graph.nodes)
.links(graph.links)
.start();
var link = svg.selectAll(".link")
.data(graph.links)
.enter().append("line")
.attr("class", "link")
.style("stroke-width", function(d) { console.log(d.value); return d.value; });
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("circle")
.attr("class", "node")
.attr("r", 10)
.style("fill", function(d) { console.log(d.name); return color(d.group); })
.call(force.drag);
node.append("title")
.text(function(d) { return d.name; });
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; });
});
});
</script>
</body>
</html>
我已经在jsonlint上测试了这个json。新线有什么不同吗?我确实读了一些关于这个的答案,但是没有一个匹配。我的源节点和目标节点在范围内,我没有空值,并且在创建JSON时我已经处理好了这个问题。事实证明,我在创建JSON文件时犯了一个愚蠢的错误。在json的链接部分,源代码的编号从0开始。因此,对于最后一个元素,I超过了该值。因此我犯了这个错误 您发布的代码中没有
weight
的实例?@RUJordan-那么这个代码对copy.json文件是如何工作的?我从上述源代码复制的json?您真的只使用这两个链接和节点吗?因为您的链接引用的是索引为29和43的节点,而这些节点将是未定义的,所以当d3尝试查找这些节点的属性时,您将得到一个错误。@AmeliaBR-我拥有的json文件非常大。因此,我没有复制/粘贴问题中的所有内容。我确实意识到有人会认为这可能是个错误。所以我对我的问题做了一些修改。
{
"nodes":[
"group": 5,
"name": "Nancie"
},
{
"group": 5,
"name": "Jonell"
}
],
"links": [
{
"source": 1,
"target": 29,
"value": 2
},
{
"source": 1,
"target": 43,
"value": 3
}
]
}