2014-09-12 65 views
0

我想多次調用我的d3代碼,並將輸出顯示在我網站的不同位置。我把代碼放在一個函數(chart)中,我試圖調用它兩次並傳遞不同的參數。d3:我的代碼會創建1個圖表但不是2

http://jsfiddle.net/5rk6g234/

我在我的D3代碼得到一個奇怪的Uncaught TypeError: undefined is not a function錯誤。 代碼運行正常,如果我只調用函數一次,但只要我做的:

chart(dj, "#c"); //dj is my data, #c is the div where I want the chart 
chart(dj, "#e"); //dj is my data, #e is the div where I want the chart 

它拋出這個錯誤,不會使第二個圖表。有什麼想法嗎?

+0

我實際上並不知道爲什麼,這沒有奏效。我環顧四周,看不到使用相同數據創建兩張圖的任何問題。但是,如果將數據複製到單獨的「變量」中,圖表將無誤地運行:http://jsfiddle.net/5rk6g234/2/ – bencripps 2014-09-12 16:21:01

回答

2

這個代碼塊,這裏面住chart()

data.forEach(function(d){ 
    d.d_string = parseDate(d.d_string); 
    d.c_string = +d.c_string; 
    }); 

它第一次運行時,它確實你所期望的東西;它將d.d_string轉換爲Date對象。雖然第二次,d.d_string已經是Date了,而d3的日期解析器只期望一個String,所以它出錯了。

如果移動的chart之外的塊(重命名datadj)它工作正常:

var parseDate = d3.time.format("%Y-%m-%d").parse; 
dj.forEach(function(d){ 
    d.d_string = parseDate(d.d_string); 
    d.c_string = +d.c_string; 
}); 

The modified fiddle

相關問題