【问题标题】:when a function's work is completed当一个功能的工作完成时
【发布时间】:2011-08-23 01:46:43
【问题描述】:

我正在使用一个 jQuery 插件,它从一个 url 获取数据,获取、计算并在 div 中写入一些数据。

我想将这个div 的内容复制到另一个div,当那个函数工作时。

例如:

$("#div1").myfunction(); // it gets and calculates data and adds to #div1 . it needs 2-3 seconds to be done
var contents = $("#div1").html(); // when myfunction() done, copy contents
$("#div2").html(contents);

当我运行该代码时,#div2 中没有新内容。

【问题讨论】:

  • myfunction 是否发出 Ajax 请求?
  • 如果myFunction() 异步完成,您需要使用回调来触发复制。
  • @karim79: jquery 执行的 ajax 调用可以是同步的。所以 - 不,它不是那么明确。

标签: javascript jquery


【解决方案1】:

你需要让myfunction 接受一个回调参数,它会在请求完成后执行

function myfunction(cb)
    $.ajax({
        type: "get",
        url: "page.html",
        success: function(data){
            $("#div1").html(data);
            if(typeof cb === 'function') cb();
        }
    });
}

myfunction(function(){
    $("#div2").html($("#div1").html());
});

【讨论】:

  • 你还要检查cb是一个有效的函数,就像这里:stackoverflow.com/questions/6792663/…
  • 假设您希望它是一个可选参数。
  • 只要它是 javascript 并且每个参数根据定义都是可选的 - 是的,这种检查是必须的
  • 所以你是说每个函数的每个参数都需要检查?无论哪种方式:添加
  • 如果您希望与您的 jQuery 版本保持同步,您应该知道 success 将在 v1.8 中被弃用。
【解决方案2】:

您只需要输入这一行:

$("#div2").html($("#div1").html());

myFunction中实现的ajax代码的成功回调中,以确保一旦客户端收到响应并将其插入到DOM中,操作就会发生。

【讨论】:

    【解决方案3】:

    Ajax 回调(例如success)将在 jQuery 1.8 中被弃用。相反,您可以使用 jQuery 的 deferred 对象来运行(或撤消)在执行之前需要更多条件的操作。

    var successFunction = function() {
      var contents = $("#div1").html();
      var newElement = $("<div id=div2></div>").html(contents);
      $("body").append(newElement);
    }
    
    var failedFunction = function() {
      // reset element or undo last change
      window.alert("Update Failed");
    }
    
    
    $.when(
      $.ajax(countParams),
      doCalculate()
    ).then(
      successFunction(),
      failedFunction()
    );
    

    Creating Responsive Applications Using jQuery Deferred and Promises

    【讨论】:

      【解决方案4】:

      如果您是编写插件的人,您应该将其硬编码到 AJAX 回调函数中,或者允许通过选项传入回调函数。

      如果您无法控制插件,则必须不断查询您的 div 以查看它是否已更新:

      var oldHTML = $("#div1").html(),
          counter = 0;
      
      $("#div1").myfunction();
      
      copyHTML();
      
      function copyHTML()
      {
          var newHTML = $("#div1").html();
      
          // we don't want this function to run indefinitely
          if (++counter > 15) return;
      
          if (newHTML == oldHTML)
              setTimeout(copyHTML, 1000);
          else
              $("#div2").html(newHTML);
      }
      

      【讨论】:

      • 如果一个插件不提供回调参数,你必须质疑它的质量......另外,添加你自己的不是火箭科学。但是您的代码如何处理失败的请求?
      • @ilia choly:完全正确!但是,在没有更好的情况下,我会选择这个。不过,我可能会增加超时时间(或在每次通话后增加超时时间)。我将它添加到警告中...
      • @ilia choly:添加了计数器以在 x 次尝试失败后停止执行。
      猜你喜欢
      • 2020-02-28
      • 2019-02-20
      • 2017-12-08
      • 1970-01-01
      • 2017-10-25
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      相关资源
      最近更新 更多