【问题标题】:Uncaught TypeError: Cannot read property 'weight' of undefined未捕获的类型错误:无法读取未定义的属性“权重”
【发布时间】:2014-05-21 15:25:20
【问题描述】:

我正在尝试在 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 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>

此代码适用于 copy.json 文件。我只是将 here 中的 json 复制粘贴到该文件中。我试图通过解析一个txt文件来创建我自己的json。当我使用我的 json 文件时,相同的代码给了我错误。这是我的 json 文件(其中的一部分) -

{
    "nodes":[
            "group": 5, 
            "name": "Nancie"
        }, 
        {
            "group": 5, 
            "name": "Jonell"
        }
    ], 
    "links": [
        {
            "source": 1, 
            "target": 29, 
            "value": 2
        }, 
        {
            "source": 1, 
            "target": 43, 
            "value": 3
        }
    ]
}

我已经在 jsonlint 上测试了这个 json。换行符有区别吗?我确实阅读了一些关于这个的答案,但没有一个匹配。我的源节点和目标节点在范围内,我没有空值,并且我在创建 JSON 时处理了这种情况。

【问题讨论】:

  • 您发布的代码中没有weight 的实例?
  • @RUJordan - 那么这段代码是如何用于 copy.json 文件的呢?我从上述来源复制的json?
  • 你真的只使用这两个链接和节点吗?因为您的链接引用索引为 29 和 43 的节点,并且这些节点未定义,所以当 d3 尝试查找这些节点的属性时,您将收到错误消息。
  • @AmeliaBR - 我拥有的 json 文件很大。所以我没有在问题中复制/粘贴所有内容。我确实意识到有人会认为这可能是错误的。所以我对我的问题做了一些修改。

标签: javascript json d3.js


【解决方案1】:

事实证明,我在创建 json 文件时犯了一个愚蠢的错误。在 json 的链接部分中,源的编号从 0 开始。因此,对于最后一个元素,我超出了该值。因此我得到了那个错误。

【讨论】:

    猜你喜欢
    • 2021-12-22
    • 2015-01-06
    • 2017-07-26
    • 2019-02-26
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多