在實際腳本工作並生成正確輸出的情況下,在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。
緩存'$(」#菜單「)'變量,循環外..它會提高性能 – rab
完成,歡呼爲此。 –