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

Javascript 如何将$(此)引用传递给回调函数?,javascript,jquery,animation,Javascript,Jquery,Animation,我的网页中有以下动画: $(".anim-item").not(this).animate({ opacity: 0, }, { queue: true, duration: 1000 } , function() { // Animation complete. }); $(this).animate({ left: 200, }, { queue: true, duration: 1000 }

我的网页中有以下动画:

     $(".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.
     });
当前两个动画同时运行。我希望第二个动画在第一个动画之后运行。我尝试将第二个放在回调函数中,但找不到使$(this)引用工作的方法。你知道怎么让它工作吗


提前感谢。

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

 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.
    });
 });

关闭内部函数将确保其可见。

为此via创建别名

var _this = this;

如果编写jQuery查询
$('.abc')
,并使用
单击
悬停
等函数,
将始终引用jQuery正在处理的当前DOM节点。

将其存储在局部变量中

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.
        });
    }
);
两种方式:

  • 调用
    .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);
};
示例2:

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);
};

在jQuery回调函数
中,此
始终设置为该函数应用的DOM元素

如果要在第一个回调函数中访问此
,则必须在设置动画之前创建对其的引用:

 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.
     });
 });

您的函数错误,如果您正在声明选项,则回调将进入选项对象:

$(".anim-item").animate({
   opacity: 1,
}, {duration: 1000, queue: true, complete: function() {
   $(this).animate({
      left: 200,
   }, { queue: true, duration: 1000, complete: function() {
      // Animation complete.
   }});
}});
另外,不要创建包含项的全局变量,这只是自找麻烦,特别是在本例中jquery将为您维护它,如果您需要在链接中为对象声明一个新变量,通常您做得不对;)