2017-02-11 91 views
0

我想創建幾個div for循環。我使用.append()和.clone方法,但div的順序是錯誤的。即使我在循環之前創建了div,在index.html第一個div(class news0)是在最後一個div(class news3)之後生成的,它應該是最後一個div。我該如何解決這個問題?使用追加,在循環克隆jquery

$news.ready(function() { 
     var query = []; 
     console.log(query); 
     $.ajax({ 
      url: baseUri + "news", 
      data: {q: query}, 
      success: showNews 
     }); 
     return false; 
    }); 

    function showNews(response) { 
     var news = response[0]; 
     console.log(news); 
     $news.append($div); 
     $div.attr('class', 'news' + 0); 
     $div.append($h1); 
     $div.append($h2); 
     $div.append($h3); 
     $div.append($p); 

     $h1.html(news.title); 
     $h2.html(news.author); 
     $h3.html(news.date); 
     $p.html(news.body); 

     for (var i = 1; i < response.length; i++) { 
      news = response[i]; 

      $news.append($div.clone()); 
      $div.attr('class', 'news' + i); 
      $div.append($h1); 
      $div.append($h2); 
      $div.append($h3); 
      $div.append($p); 

      $h1.html(news.title); 
      $h2.html(news.author); 
      $h3.html(news.date); 
      $p.html(news.body); 
     } 
    } 

screenshot

回答

0

你的情況divs的順序是由於JavaScript的for循環的異步特性不恰當的。你可以做的是使用jQuery的是synchronous$.each功能,因此會給你所需的輸出

您與$.each()循環功能會像

function showNews(response) { 
    var news = response[0]; 
    console.log(news); 
    $news.append($div); 
    $div.attr('class', 'news' + 0); 
    $div.append($h1); 
    $div.append($h2); 
    $div.append($h3); 
    $div.append($p); 

    $h1.html(news.title); 
    $h2.html(news.author); 
    $h3.html(news.date); 
    $p.html(news.body); 

    $.each(reponse, function(index, news){ 
     if(index > 0) { 
     $news.append($div.clone()); 
     $div.attr('class', 'news' + i); 
     $div.append($h1); 
     $div.append($h2); 
     $div.append($h3); 
     $div.append($p); 

     $h1.html(news.title); 
     $h2.html(news.author); 
     $h3.html(news.date); 
     $p.html(news.body); 
     } 

    }) 

} 
+0

這並不求解帶的問題。現在我有4個div,但首先是空的。 – pawell67

+0

我更新了代碼,我覺得應該幫忙 –

+0

不幸的是,div的順序又是3-0-1-2。 – pawell67