2014-08-28 6 views
0

Каждый раз, когда я пытаюсь показать ингредиенты для каждого Diner.Lunch, он продолжает показывать ингредиенты двойными без причины. Кажется, я действительно не могу найти ошибку.JQUERY + JSON weird error

$('.Lunch_article').append("<h3>Ingredients</h3> <ul>"); 

Так что эта часть шоу двойной, а затем 1 раз в одиночку, но это хорошо причина это то, что код должен делать ($.each(data[0].Dishes[0].Lunch, function(i))

Я не знаю, как создать JSfiddle (с JSON), но я не думаю, что это neccesary, потому подытожил он выглядит следующим образом:

Ингредиенты
Ингредиенты

Ингредиенты

, который мне нужен, чтобы выглядеть следующим образом:
Ингредиенты

Ингредиенты

$(document).ready(function(){ 

    $(".diner_section").empty(); 

    $.ajax(
       { 
        url:  'Menu.json', 
        dataType: 'json', 
        success: function(data) 
        { 
         $(".lunch_section h2").remove(); 
         $('.lunch_section').append("<h2 class='sectiontitel on'> <span> Lunch </span> </h2>"); 
         $('article.Lunch_article').remove(); 
         $.each(data[0].Dishes[0].Lunch, function(i) 
         { 

          $('.lunch_section').append("<article class='Lunch_article'> <img src='" 
           + data[0].Dishes[0].Lunch[i].Image 
           + "' alt='food_image'> <h1>" 
           + data[0].Dishes[0].Lunch[i].Name 
           + "</h1> <p>" 
           + data[0].Dishes[0].Lunch[i].description 
           + "</p>"); 

          $('.Lunch_article').append("<h3>Ingredients</h3> <ul>"); 
          $.each(data[0].Dishes[0].Lunch[i].ingredients[0], function(k, val) 
          { 
           console.log(data[0].Dishes[0].Lunch[i].ingredients[0]); 
           $('.Lunch_article ul').append("<li>" + val + "</li>") 
          }); 


         });   

        }, 

        // eventuele foutafhandeling.... 
        error: function() 
        { 
         alert("Houston, we have a problem"); 
        } 
    }); 
}); 

HTML:

<section class="lunch_section"> 
    <h2 class="sectiontitel"> <span> Lunch </span> </h2> 
    <article class="Lunch_article"> 
     <img src="Images/lunch/bentobox.jpg" alt="food_image"/> 
     <h1> Bento Box </h1> 
     <p>Bento is a single-portion takeout or home-packed meal common in Japanese cuisine. A traditional bento holds rice, fish or meat, with pickled or cooked vegetables, usually in a box-shaped container. Containers range from disposable mass produced to hand crafted lacquerware. Bento boxes are readily available in many places throughout Japan, including convenience stores, bento shops, railway stations, and department stores. However, Japanese homemakers often spend time and energy on a carefully prepared lunch box for their spouse, child, or themselves.<br /> <a href="http://en.wikipedia.org/wiki/Bento"> Read more </a></p> 
     <h3>Ingredients</h3> 
     <ul> 
     <li>Rice</li> 
     <li>Fish</li> 
     <li>Seaweed</li> 
     <li>Soy Sause</li> 
     <li>Vegetables</li> 
     <li>Fish</li> 
     </ul> 

    </article> 

    </section> 

JSON:

[ 
    { 
     "Dishes": 
     [ 
      { 
       "Lunch": 
       [ 
        { 
         "Name":"Bento Box", 
         "type":"main", 
         "Image":"Images/lunch/bentobox.jpg", 
         "description":"Bento is a single-portion takeout or home-packed meal common in Japanese cuisine. A traditional bento holds rice, fish or meat, with pickled or cooked vegetables, usually in a box-shaped container. Containers range from disposable mass produced to hand crafted lacquerware. Bento boxes are readily available in many places throughout Japan, including convenience stores, bento shops, railway stations, and department stores. However, Japanese homemakers often spend time and energy on a carefully prepared lunch box for their spouse, child, or themselves.", 
         "url":"http://en.wikipedia.org/wiki/Bento", 
         "ingredients": 
           [ 
            { 
             "no1":"Rice", 
             "no2":"Fish", 
             "no3":"Seaweed", 
             "no4":"Soy Sause", 
             "no5":"vegetables", 
             "no6":"meat" 
            } 
           ] 
        }, 
        { 
         "Name":"Miso Soup", 
         "type":"entree", 
         "Image":"Images/lunch/miso.jpg", 
         "description":"Miso soup (misoshiru?) is a traditional Japanese soup consisting of a stock called \"dashi\" into which softened miso paste is mixed. Many ingredients are added depending on regional and seasonal recipes, and personal preference.", 
         "url":"http://en.wikipedia.org/wiki/Miso_soup", 
         "ingredients": 
           [ 
            { 
             "no1":"Dashi", 
             "no2":"Tofu", 
             "no3":"Miso Paste" 
            } 
           ] 
        } 

       ], 


       "Diner": 
        [ 
         { 
          "Name":"Sake Nigiri", 
          "type":"Nigiri", 
          "Image":"Images/diner/sake_nigiri.jpg", 
          "description":"Nigirizushi (\"hand-pressed sushi\") consists of an oblong mound of sushi rice that the chef presses into a small rectangular box between the palms of the hands, usually with a bit of wasabi, and a topping (the neta) draped over it. Neta are typically fish such as salmon, tuna or other seafood. Certain toppings are typically bound to the rice with a thin strip of nori, most commonly octopus (tako), freshwater eel (unagi), sea eel (anago), squid (ika), and sweet egg (tamago). One order of a given type of fish typically results in two pieces, while a sushi set (sampler dish) may contain only one piece of each topping", 
          "url":"http://en.wikipedia.org/wiki/Sushi", 
          "ingredients": 
            [ 
             { 
              "no1":"Rice", 
              "no2":"Salmon", 
              "no3":"Wasabi paste", 
              "no4":"Soy Sause" 
             } 
            ] 
         }, 

         { 
          "Name":"Sake Maki", 
          "type":"Maki", 
          "Image":"Images/diner/Sake_maki.jpg", 
          "description":"Makizushi (\"rolled sushi\"), norimaki (\"Nori roll\") or makimono (\"variety of rolls\") is a cylindrical piece, formed with the help of a bamboo mat known as a makisu. Makizushi is generally wrapped in nori (seaweed), but is occasionally wrapped in a thin omelette, soy paper, cucumber, or shiso (perilla) leaves. Makizushi is usually cut into six or eight pieces, which constitutes a single roll order. Below are some common types of makizushi, but many other kinds exist.", 
          "url":"http://en.wikipedia.org/wiki/Sushi", 
          "ingredients": 
            [ 
             { 
              "no1":"Rice", 
              "no2":"Seaweed", 
              "no3":"Salmon" 
             } 
            ] 
         }, 

         { 
          "Name":"Sake Temaki", 
          "type":"Temaki", 
          "Image":"Images/diner/sake_temaki.jpg", 
          "description":"Temaki (\"hand roll\") is a large cone-shaped piece of nori on the outside and the ingredients spilling out the wide end. A typical temaki is about ten centimeters (4 in) long, and is eaten with fingers because it is too awkward to pick it up with chopsticks. For optimal taste and texture, temaki must be eaten quickly after being made because the nori cone soon absorbs moisture from the filling and loses its crispness, making it somewhat difficult to bite through. For this reason, the nori in pre-made or take-out temaki is sealed in plastic film which is removed immediately before eating.", 
          "url":"http://en.wikipedia.org/wiki/Sushi", 
          "ingredients": 
            [ 
             { 
              "no1":"Rice", 
              "no2":"Salmon", 
              "no3":"Wasabi paste", 
              "no4":"Avocado", 
              "no4":"Seaweed" 
             } 
            ] 
         } 

        ] 
       } 
      ] 
     } 
    ] 
+0

Как выглядит ваш HTML-код – ASG

+0

на полузависимой ноте, похоже, что вы создадите более 1 тэг 'h1' с вашими циклами. С точки зрения лучшей практики теги 'h1' должны отображаться только один раз на странице. – haxxxton

+0

[Вы уже спрашивали об этом] (http://stackoverflow.com/questions/25527882/json-wont-load). Спрашивать снова - это не путь. –

ответ

1

От the documentation for .append:

Вы можете создавать контент и вставить его в несколько элементов одновременно:

$(".inner").append("<p>Test</p>"); 

Каждый внутренний элемент получает это новое содержание:

<h2>Greetings</h2>  
<div class="container">  
    <div class="inner">  
    Hello  
    <p>Test</p>  
    </div>  
    <div class="inner">  
    Goodbye  
    <p>Test</p>  
    </div>  
</div> 

Я считаю, что это ваша проблема, каждый раз вы звоните

заголовок Ингредиенты прилагается ко всем экземплярам L unch, а не только тот, который вы сейчас просматриваете. Итак, в двух статьях вы получаете дважды печатаемые ингредиенты в первом, а затем один раз во втором. Чтобы исправить это, вам нужно предоставить каждой статье обеда уникальный идентификатор и добавить только к этому.

+0

Wowww !!! Я думаю ты прав! Я попробую прямо сейчас! – stackkieboy

+0

Да, это исправление. Вы можете видеть, как он работает здесь: http://jsfiddle.net/ffLw8w86/4/ –

+0

Спасибо, ребята !!! Гении !! – stackkieboy