Passing $(this) to a callback in jQuery?

本小妞迷上赌 提交于 2019-12-17 20:39:02

问题


I have two effects that I want to run one after another, but I can't work out how to pass $(this) to the callback from the first effect.

This is what I have at the moment:

if($(this).hasClass('flag')) {
    $('someElement').slideUp();
    $(this).slideDown();
}

But what I want is for the slideDown to run after the slideUp is complete, ie.

if($(this).hasClass('flag')) {
    $('someElement').slideUp(function() {
        $(this).slideDown();
    });
}

Except $(this) by that stage now refers to someElement instead and so doesn't work as planned.

How do I refer to my original element.flag. I tried using $this = $(this) but I think I must have the syntax wrong.

Any ideas?


回答1:


Save the reference.

if($(this).hasClass('flag')) {
    var el = this;
    $('someElement').slideUp(function() {
        $(el).slideDown();
    });
}



回答2:


cache it like this... just don't forget thevar.

var $this = $(this);
if($this.hasClass('flag')) {
    $('someElement').slideUp(function() {
        $this.slideDown();
    });
}



回答3:


Give this a shot:

var self = $(this);
if(self.hasClass('flag')) {
    $('someElement').slideUp(function() {
        self.slideDown();
    });
}


来源:https://stackoverflow.com/questions/5086828/passing-this-to-a-callback-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!