簡體   English   中英

在getJSON中使用每個函數將返回未定義

[英]Using the each function within getJSON returns undefined

我正在使用jQuery的getJSON方法來檢索和解析一個簡單的JSON文件,但是當我將值輸出到頁面上時,它顯示為undefined

$.getJSON( 'js/example.json', function ( data ) {

    var output = '';

    $.each( data.exercises, function ( index, exercise ) {
        output += '<li>' + exercise.work.weight + ' x ' + exercise.work.reps  + '</li>';
    });

    $( '#example' ).html( output );

});

example.json

{

    "exercises" : [

        {
            "name" : "Squats",
            "work" : [
                {
                    "weight" : 135,
                    "reps" : 5
                },
                {
                    "weight" : 225,
                    "reps" : 5
                },
                {
                    "weight" : 315,
                    "reps" : 5
                }
            ]

        },
        {
            "name" : "Bench",
            "work" : [
                {
                    "weight" : 135,
                    "reps" : 5
                },
                {
                    "weight" : 225,
                    "reps" : 5
                },
                {
                    "weight" : 315,
                    "reps" : 5
                }
            ]

        },
        {
            "name" : "Rows",
            "work" : [
                {
                    "weight" : 135,
                    "reps" : 5
                },
                {
                    "weight" : 225,
                    "reps" : 5
                },
                {
                    "weight" : 315,
                    "reps" : 5
                }
            ]

        }

    ]


}

我認為錯誤可能出在我的每個函數中,但我還無法識別出它。 有任何想法嗎?

您的鍛煉工作是一個數組,需要另一個循環

$.each( data.exercises, function ( index, exercise ) {
    $.each(exercise.work, function (index, work) {
         console.log(work);
    });
});

這個:

output += '<li>' + exercise.work.weight + ' x ' + exercise.work.reps  + '</li>';

假設您的JSON如下所示:

"exercises" : [
  {
    "name" : "Squats",
    "work" : 
      {
        "weight" : 135,
        "reps" : 5
      }
  },

實際上,在每種情況下, work都是一個數組。

您想要類似的東西:

$.each( data.exercises, function ( index, exercise ) {

   $.each( exercise.work, function( index, workout ) { 
      output += '<li>' + workout.weight + ' x ' + workout.reps  + '</li>';
   });

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM