2014-02-12 83 views
0

這是從HTML文件我的代碼腳本標記錯誤鏈接沒有定義

var links; 
d3.json("sample.json",function(json){links=json;}); 

var inputlinks=[]; 
var nodes = {}; 

inputlinks.push(links); 
// Compute the distinct nodes from the links. 
links.forEach(function(link) { 
link.source = nodes[link.source] || (nodes[link.source] = {name: link.source, type:link.type}); 
link.target = nodes[link.target] || (nodes[link.target] = {name: link.target, type:link.typeKBP}); 
    }); 

在這段代碼我得到一個錯誤

TypeError: links is undefined 
    links.forEach(function(link) 
+0

'd3.json'是一個異步調用嗎? –

回答

2

正如在評論中指出,d3.json是異步調用。這意味着處理函數中的代碼將在返回時運行,而不是立即運行。它後面的代碼雖然立即運行。

要修復,移動代碼的其餘部分的處理函數中:

d3.json("sample.json",function(json){ 
    var links = json; 
    var inputlinks=[]; 
    var nodes = {}; 

    inputlinks.push(links); 
    // Compute the distinct nodes from the links. 
    links.forEach(function(link) { 
    link.source = nodes[link.source] || (nodes[link.source] = {name: link.source, type:link.type}); 
    link.target = nodes[link.target] || (nodes[link.target] = {name: link.target, type:link.typeKBP}); 
    }); 
}); 
2

從你提供我只能猜測,你應該包括所有的loginc inide回調的信息:

var links; 
d3.json("sample.json",function(json){ 
    links=json; 
    var inputlinks=[]; 
    var nodes = {}; 

    inputlinks.push(links); 
    // Compute the distinct nodes from the links. 
    links.forEach(function(link) { 
    link.source = nodes[link.source] || (nodes[link.source] = {name: link.source, type:link.type}); 
    link.target = nodes[link.target] || (nodes[link.target] = {name: link.target, type:link.typeKBP}); 
    }); 
});