【问题标题】:Run function once only after load()仅在 load() 之后运行函数一次
【发布时间】:2015-09-21 09:11:12
【问题描述】:

我正在使用 jquery load() 加载多个项目。一切正常。

for(i = 0; i<item.length; i++){
   $( '#parent'+i).load('file'+i+'.html',function(){
       customFunctions();
   });
}

我的问题是,我需要在所有加载完成后运行customFunctions()。我上面的代码多次运行它。如何在所有文件加载完成后才运行一次customFunctions()

【问题讨论】:

标签: javascript jquery


【解决方案1】:

这是关于做出承诺,但你也可以这样做:

var all_loaded = 0;

for(var i = 0; i < item.length; i++){
   $( '#parent' + i).load('file' + i + '.html',function(){
      ++all_loaded == item.length && customFunctions();
   });
}

//++all_loaded: mean It is sum +1 when a file is loaded

所以当all_loaded 等于item.length 时,函数会在最后加载。

【讨论】:

  • 但仍然没有解释for循环的目的
  • @Becky 我不是发帖人,但这是if(++all_loaded == item.length) customFunctions();的快捷方式
  • @Becky 等价于if(++all_loaded == item.length){ customFunctions() }
  • @Becky 简而言之就是一种做事方式。看到这个answer
  • ++all_loaded 意思是变量的总和+1。相当于:all_loaded += 1
【解决方案2】:

添加计数器并在每个文件加载时更新它。当计数器的当前值等于您要加载的文件总数时,调用您的函数;

【讨论】:

    【解决方案3】:
    for(var i = 0; i<item.length; i++){
       $( '#parent').load('file.html',function(){
          if(i==(item.length-1))
              customFunctions();
       });
    }
    

    这应该可行。

    【讨论】:

      【解决方案4】:

      试试这个:

      只有当所有加载请求都成功时,你的函数才会运行

      var item = {length:12};
      runfunction = 0;
      for(i = 0; i<item.length; i++){
         $( '#parent').load('t.html',function(responseText, textStatus, XMLHttpRequest){
      
            if (textStatus == "success") {
                  runfunction++;
             }
             /* you can write three line of code any where even after for loop according to your requirements*/
             if(runfunction == item.length ){
              customFunctions();
             }
         });
      }
      
      function customFunctions(){
       alert(1);
      }
      

      【讨论】:

        【解决方案5】:

        有很多选择。

        您可以在循环中跟踪:

        var loadedCount = 0;
        for(i = 0; i<item.length; i++){
          $( '#parent').load('file.html',function(){
            loadedCount++;
            if (loadedCount === item.length) {
              customFunctions();
            }
          });
        }
        

        这将完成这个特定案例的工作。这仅适用于在这种受限设计中,您知道自己调用了多少次,并且可以相信/相信您的 AJAX 请求都不会失败。因此,它不是一个非常稳定的设计。

        【讨论】:

          猜你喜欢
          • 2016-07-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-10-15
          • 2021-05-29
          • 1970-01-01
          • 2018-05-10
          相关资源
          最近更新 更多