0

当实际脚本工作并生成正确的输出时,在 Chrome 控制台中出现上述错误,想知道我怎样才能摆脱这个错误以及导致它的原因。

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 格式输出。

4

2 回答 2

1

for 循环条件不正确。

您使用j = data[0].weekending.length了等于 10 的值,并且您正在迭代data[0].jobs只有 3 个作业的对象。您对作业进行了 3 次以上的迭代,因此您遇到了错误。

签出小提琴http://jsfiddle.net/wJUeP/7/

于 2013-10-10T07:31:19.470 回答
0

错误在这里:

j = data[0].weekending.length

这将返回 10,这是周末属性中字符串的长度 == 10 ("09/10/2013") 我认为您需要这个:

j = data[0].jobs.length
于 2013-10-10T07:48:54.733 回答