getJSON和$ .each给了我错误的值

时间:2014-09-18 13:57:18

标签: jquery json

我有以下JSON对象:

{
"pages": [
    {
        "id": "0",
        "title": "Some persons name | Author",
        "datatarget": "#navBarMain",
        "page": "imports/nav.html",
        "keywords": "some keywords go here"
    },
    {
        "id": "1",
        "title": "Some persons name | Author",
        "datatarget": "#authorname",
        "page": "imports/about-author.html",
        "keywords": "some more keywords go here"
    }//,
   ... more elements could go here...

}

当我运行以下代码时:

// JQUery Fancy Box
$(document).ready(function () {

    //Load Imports
    //Navigation
    $(function () {

        var divs = "scripts/json-objects/divIDs.json";
        var jqxhr = $.getJSON(divs, function (data) {
            //Attaching the events in the callback function of .load
        //Load the pages
            $.each(data, function (key, val) {
                $(key[val].datatarget).load(key[val].page, function () {
                    $('.navbar-nav .nav li a, .navbar-brand a, a[data-target]').click(function () { //This is what's not working
                        $('html, body').animate({
                            scrollTop: $($(this).attr('data-target')).offset().top - 80
                        }, 500);

                    });
                });
            });

        }).done(function () {
            console.log("second success");
        }).fail(function (jqxhr, textStatus, error) {
            var err = textStatus + ", " + error;
            console.log("Request Failed: " + err);
        }).always(function () {
            console.log("complete");
        });
    });
});

我在控制台中收到以下错误:

enter image description here

我已经用这个问题绞尽脑汁待了几个小时。

发生的事情是KEY以“页面”形式出现,而“val”是实际数组。

所以我认为我的逻辑中的某些事情是倒退的

拜托,我想要第二眼。

谢谢

1 个答案:

答案 0 :(得分:2)

您需要循环data.pages,因为包含对象数组的内容和$.each的回调参数为(key, value)valuedata.pages[key]

var jqxhr = $.getJSON(divs, function(data) {
    $.each(data.pages, function(key, val) {
        $(val.datatarget).load(val.page, function() {
            $('.navbar-nav .nav li a, .navbar-brand a, a[data-target]').click(function() {
                $('html, body').animate({
                    scrollTop: $($(this).attr('data-target')).offset().top - 80
                }, 500);
            });
        });
    });
});