2017-07-26 73 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; 
     }; 
     }; 
    });  
    });