【问题标题】:JQuery click 1 does nothingJQuery click 1 什么都不做
【发布时间】:2018-01-02 11:08:18
【问题描述】:

我感觉我的 for 循环有问题。当我的网站事件第一次被激活时,我没有得到任何回应。之后每次都按预期工作。我已经尝试调整 for 循环中的数字以查找错误,但就我所尝试的而言。效果最好。

完整应用: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;
    };
  };
});

【问题讨论】:

  • 第一次为我工作。
  • 这与 reference[0] 排在第一位有关。如果我运行我的 ajax 函数 random();在我的 jquery 之前它按预期工作。

标签: javascript ajax for-loop


【解决方案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;
        };
      };
    });    
  });

【讨论】:

    猜你喜欢
    • 2015-05-19
    • 2019-08-20
    • 1970-01-01
    • 2019-03-08
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 1970-01-01
    • 2015-11-29
    相关资源
    最近更新 更多