代码之家  ›  专栏  ›  技术社区  ›  Niyaz

如何将$(this)引用传递给回调函数?

  •  2
  • Niyaz  · 技术社区  · 14 年前

    我的网页中有以下动画:

         $(".anim-item").not(this).animate({
            opacity: 0,
         }, { queue: true, duration: 1000 } , function() {
            // Animation complete.
         });
    
         $(this).animate({
            left: 200,
         }, { queue: true, duration: 1000 } , function() {
            // Animation complete.
         });
    

    提前谢谢。

    6 回复  |  直到 14 年前
        1
  •  3
  •   Psytronic    14 年前

    你的功用不对

    $(".anim-item").animate({
       opacity: 1,
    }, {duration: 1000, queue: true, complete: function() {
       $(this).animate({
          left: 200,
       }, { queue: true, duration: 1000, complete: function() {
          // Animation complete.
       }});
    }});
    

    另外,不要创建一个包含该项的全局变量,这只是自找麻烦,特别是在这个实例中jquery将为您维护它,如果您需要在链接中为对象声明一个新变量,通常您做得不对;)

        2
  •  1
  •   falstro    14 年前

    以其他名称保存,如下所示:

     var myThis = this;
     $(".anim-item").not(this).animate({
        opacity: 0,
     }, { queue: true, duration: 1000 } , function() {
        $(myThis).animate({
           left: 200,
        }, { queue: true, duration: 1000 } , function() {
           // Animation complete.
        });
     });
    

    关闭内部函数将确保它是可见的。

        3
  •  1
  •   jAndy    14 年前

    • 隐藏物 this 在调用 .animate()
    • 使用 .proxy() 通过你的 参考 .animate()

    例1:

    var func = function(){
       var self = this;
    
       $(".anim-item").not(this).animate({
         opacity: 0,
         }, { queue: true, duration: 1000 } , function() {
            self.animate({});
         });
    };
    

    var func = function(){
       $.proxy($(".anim-item").not(this).animate({
       }), this);
    };
    
        4
  •  0
  •   Marcel Jackwerth    14 年前

    为此via创建别名

    var _this = this;
    

    如果您编写jQuery查询 $('.abc') 使用如下函数 click , hover 等, this

        5
  •  0
  •   Elie    14 年前

    将其存储在局部变量中。

    var _this = this;
    
    $(".anim-item").not(this).animate({
            opacity: 0,
        }, { queue: true, duration: 1000 } , function() {
            // Animation complete. Next animation
            $(_this).animate({
                left: 200,
            }, { queue: true, duration: 1000 } , function() {
                // Animation complete.
            });
        }
    );
    
        6
  •  0
  •   klaaspieter    14 年前

    在jQuery回调函数中 this

    如果你想进入 在第一个回调函数中,必须先创建对它的引用,然后才能设置动画:

     var self = this;
     $(".anim-item").not(this).animate({
        opacity: 0,
     }, { queue: true, duration: 1000 } , function() {
        $(self).animate({
            left: 200,
         }, { queue: true, duration: 1000 } , function() {
            // Animation complete.
         });
     });