2013-10-10 131 views
0

在實際腳本工作並生成正確輸出的情況下,在Chrome控制檯中獲取上述錯誤,想知道如何擺脫此錯誤以及導致錯誤的原因。未捕獲的類型錯誤:無法讀取未定義的屬性x

的jsfiddle:http://jsfiddle.net/wJUeP/

HTML代碼:

<ul id="menu"></ul> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 

JS代碼:

$(function(){ 
var data = [{"weekending":"09\/10\/2013","jobs":[{"jobnumber":"1001","jobaddress":"Test1001","employees":[{"employeenumber":"1","name":"James Blabla","class":"FHM","notes":"xx","nt-wkmon":"2","t12-wkmon":"5","dt-wkmon":"4","status-wkmon":"Public Holiday","startTime-wkmon":"4","finishTime-wkmon":"6","nt-wktue":"7"}]},{"jobnumber":"1002","jobaddress":"Test1002","employees":[{"employeenumber":"1","name":"Cameron Le","class":"FHQ","notes":"xx","nt-wkmon":"2","t12-wkmon":"5","dt-wkmon":"4","status-wkmon":"Public Holiday","startTime-wkmon":"4","finishTime-wkmon":"6","nt-wktue":"7"},{"employeenumber":"2","name":"David Le","class":"FHQ","notes":"xx","nt-wkmon":"2","t12-wkmon":"5","dt-wkmon":"4","status-wkmon":"Public Holiday","startTime-wkmon":"4","finishTime-wkmon":"6","nt-wktue":"7"}]},{"jobnumber":"1003","jobaddress":"Test1003","employees":[{"employeenumber":"1","name":"Nick G","class":"sdf","notes":"sdf","nt-wkmon":"2","t12-wkmon":"5","dt-wkmon":"4","status-wkmon":"Public Holiday","startTime-wkmon":"4","finishTime-wkmon":"6","nt-wktue":"7"}]}]}]; 

for(var i = 0, j = data[0].weekending.length; i<j; i++) { 
    rootMenu = data[0].jobs[i]; 
    $("#menu").append("<li id='job_" + rootMenu.jobnumber + "'>" + rootMenu.jobnumber); 
    if(rootMenu.hasOwnProperty("employees")) { 
     $("#menu").append("<ul id='employees_job_" + rootMenu.jobnumber + "'>"); 
     for(var n = 0, m = rootMenu.employees.length; n<m; n++) { 
      var subMenu = rootMenu.employees[n]; 
      if(subMenu.hasOwnProperty("name")) { 
       $("#employees_job_" + rootMenu.jobnumber).append("<li>" + subMenu.name + "</li>"); 
      } 
     } 
     $("#menu").append("</ul>"); 
    } else { 
     $("#menu").append("</li>"); 
    } 
} 
}); 

注:我仍然在我的應用程序的開發階段,我可以靈活地更改和操作數據結構,如果嵌入式JSON數據看起來不好我可以更改它,實際數據存儲在XML文件中,然後通過PHP讀取並輸出爲JSON。

+1

緩存'$(」#菜單「)'變量,循環外..它會提高性能 – rab

+0

完成,歡呼爲此。 –

回答

1

for循環條件不正確。

您已使用j = data[0].weekending.length,它等於10,並且您正在迭代僅有3個作業的data[0].jobs對象。你在作業上迭代了3次以上,因此你得到了錯誤。

結帳小提琴http://jsfiddle.net/wJUeP/7/

+0

完美感謝你 –

+0

很高興它幫助你:) – Abhidev

0

錯誤是在這裏:

j = data[0].weekending.length 

這是返回10,這是在週末度假屬性== 10的字符串的長度(「2013年9月10日「) 我認爲你需要這個:

j = data[0].jobs.length 
相關問題