2016-12-01 365 views
-2

我正嘗試使用jqplot創建餅圖,但出現標題中顯示的錯誤。最終,我想使用下面的代碼來創建不同類型的jqplot圖表,因爲數據格式基本相同。在的for循環retrieveData()是我將創建數據,將填充將生成餅圖或條形圖的所有項目數組。我想先讓它爲餅圖工作。您還可以找到https://jsfiddle.net/isogunro/5peuchqe/未捕獲TypeError:無法讀取未定義的屬性'addItems'

var schoolApp = window.schoolApp || {}; 
schoolApp.itemType = new Array(); 

$(document).ready(function() { 
retrieveData(); 
}); 

function retrieveData() { 
var allItems = new getItems(); 

var k=0; 
for (i=0; i<10; i++){ 
k +=i; 
window.allItems.addItems("Hello"+i, k); 
} 

chartArray = window.allItems.getChartData(); 

plotChart(chartArray); 
} 

function getItems() { 
this.inputs = {}; 
this.items = []; 

this.addItems = function (unqItem, amount1) { 
    if (!this.inputs[unqItem]) { 
     this.items.push(unqItem); 
     this.inputs[unqItem] = 0; 
    } 
    this.inputs[unqItem] += amount1; 
}; 

this.getChartData = function() { 
    var chartAry = []; 
    for (i = 0; i < this.items.length; ++i) { 
     chartAry.push([this.items[i], this.inputs[this.items[i]]]); 
    } 
    return chartAry; 
} 

} // end of function truck2pie 


function plotChart(data) { 

var plot1 = jQuery.jqplot('pieChart', [data], 
{ 
    seriesDefaults: { 
     // Make this a pie chart. 
     renderer: jQuery.jqplot.PieRenderer, 
     rendererOptions: { 
      fill: true, 
      sliceMargin: 7, 
      dataLabels: 'value', //Show data instead of label 
      showDataLabels: true, 
      linewidth: 5, 
      shadowOffset: 2, 
      shadowDepth: 5, //Number of strokes to make when drawing shadow. Each stroke offset by shadowOfset from the last. 
      shadowAlpha: 0.07 
     } 
    }, 
    legend: { show: true, location: 'e' } 
} 
); 

} 
+2

的錯誤是很清楚的,your're試圖訪問一個不存在的屬性:'window.allItems'是不確定的,所以你不能。 – DCruz22

+0

[檢測未定義對象屬性]的可能重複(http://stackoverflow.com/questions/27509/detecting-an-undefined-object-property) –

回答

1

你不使用window訪問一個局部變量,只是將其刪除,它會工作。

function retrieveData() { 
     var allItems = new getItems();  
     var k=0; 
     for (i=0; i<10; i++){ 

     k +=i; 
     allItems.addItems("Hello"+i, k); 
    } 

    chartArray = allItems.getChartData(); 

    plotChart(chartArray); 
} 

function getItems() { 
    this.inputs = {}; 
    this.items = []; 

this.addItems = function (unqItem, amount1) { 
    if (!this.inputs[unqItem]) { 
     this.items.push(unqItem); 
     this.inputs[unqItem] = 0; 
    } 
    this.inputs[unqItem] += amount1; 
}; 

this.getChartData = function() { 
    var chartAry = []; 
    for (i = 0; i < this.items.length; ++i) { 
     chartAry.push([this.items[i], this.inputs[this.items[i]]]); 
    } 
    return chartAry; 
} 

}

相關問題