weixin_33709590 2017-07-26 22:42 采纳率: 0%
浏览 35

jQuery单击1什么都不做

I have a feeling there is something wrong with my for loop. When my websites event is activated the first time, I get no response. It works as intended every time after that. I have tried tuning the numbers in the for loop looking for mistakes but as far as what I've tried. It works best as is.

For the full app: 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条回答 默认 最新

  • weixin_33720452 2017-07-27 00:09
    关注

    Your rest of the code ran before your ajax push the value to reference variable.

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

    You can either put your page rendering code within the ajax or use some tips to run the rederer synchronously

    $("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;
            };
          };
        });    
      });
    
    评论

报告相同问题?