【问题标题】:How to call function only for first time in loop如何仅在循环中第一次调用函数
【发布时间】:2016-10-25 18:27:10
【问题描述】:

在这里,我有一组动画将继续循环,我试图仅在第一次迭代时调用该函数,当第一次迭代结束时,不应再调用该函数。我该怎么做?

这是我的代码

             var r5anim1 = function(){
                $(".r5").velocity({ 
                      opacity: 1,
                      scale: [1,0],
                    }, {
                    duration:300,
                    complete: function() {
                    r5anim2();
                    }
                });
             }  

            var r5anim2 = function(){
                $(".r5").velocity({ 
                  opacity: 0,
                },{
                    duration:200,
                    complete: function() {
                    r6anim1();
                    wishes() // here i have called the function which should execute only on first loop.
                }               
            });
            }

            var r6anim1 = function(){
                $(".r6").velocity({ 
                      opacity: 1,
                      scale: [1,0],
                    }, {
                    duration:300,
                    complete: function() {
                    r6anim2();
                    }
                });
             }  

            var r6anim2 = function(){
                $(".r6").velocity({ 
                  opacity: 0,
                },{
                    duration:200,
                complete: function() {                                         
                    r5anim1();       //on end this will start the loop again 
                }               
            });
            }




        /*****************this function should be called only for the first time******************/
        var wishes = function(){
            boolvalue = 0;
            $(".wishes").velocity({ 
                  opacity: 1,
                  scale: [1,0.4],
                }, {
                duration:600,
            });
         }  
        r5anim1();

【问题讨论】:

  • 在循环外声明一个临时变量并设置默认为true,如果它的调用函数为true,则在循环中检查它一旦被调用的函数使其为false

标签: jquery velocity.js


【解决方案1】:

创建一个全局变量

var isTriggered = false;

测试isTriggered,如果不是tigger调用函数

if(!isTriggered)
 {
wishes()
}

在 wish() 函数中将变量更改为 true,以便循环停止

function wishes() {
isTriggered = false;
//other code
}

【讨论】:

    【解决方案2】:

    您必须创建一个可全局访问的变量,并将其默认为 false

    var isFunctionCalled = false;
    

    仅在标志为 false 时调用该函数,并在调用函数时将标志更改为 true。

    if(isFunctionCalled == false){
        wishes()
        isFunctionCalled = true;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      • 2011-05-16
      • 1970-01-01
      相关资源
      最近更新 更多