2017-07-26 72 views
2

我有一種感覺,我的循環出現問題。當我的網站事件第一次被激活時,我沒有得到任何迴應。它隨後每次都按預期工作。我試着調整for循環中的數字來尋找錯誤,但是儘可能的我嘗試過。它的效果最好。JQuery單擊1什麼也不做

對於整個應用程序:https://codepen.io/xcidis/full/KvKVZb/

var reference = []; 

function random() { 
    $.ajax({ 
     url: "https://api.forismatic.com/api/1.0/?", 
     dataType: "jsonp", 
     data: "method=getQuote&format=jsonp&lang=en&jsonp=?", 
     success: function(quote) { 
     reference.push([quote.quoteText + "<br/><br/><br/><div align='right'>~" + quote.quoteAuthor + "</div>"]); 
     } 
    }); 
} 

$("button").click(function(){ 
    random(); 
    for(i=0;i<4; i++){ 
    if(reference[reference.length-1] == undefined){continue}else{ 
    var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>"); 
    $('body').append(boxes); 
     break; 
    }; 
    }; 
}); 
+1

曾爲我第一次。 – Andy

+0

它與參考文獻[0]是第一個在線。如果我運行我的ajax函數random();在我的jquery之前它按預期工作。 –

回答

1

你的代碼的其餘跑到你的Ajax推引用變量的值了。

https://www.w3schools.com/xml/ajax_intro.asp

你可以把你的網頁渲染代碼Ajax的範圍內或使用一些技巧來運行rederer同步

$("button").click(function(){ 
    $.when( $.ajax({ 
     url: "https://api.forismatic.com/api/1.0/?", 
     dataType: "jsonp", 
     data: "method=getQuote&format=jsonp&lang=en&jsonp=?", 
     success: function(quote) { 
     reference.push([quote.quoteText + "<br/><br/><br/><div class='tweet' align='left'></div><div align='right'>~" + quote.quoteAuthor + "</div>"]); 
     } 
    })).then(function() { 
     console.log(reference) 
     for(i=0;i<4; i++){ 
     if(reference[reference.length-1] == undefined){continue}else{ 
     var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>"); 
     $('body').append(boxes); 
      break; 
     }; 
     }; 
    });  
    });