简体   繁体   中英

Javascript - using $(this) in a function inside a function?

Basically, there is a screen and if you link a button, the screen slides up and then another screen appears. The problem is, the slideUp() function takes some time to execute and the other screen appears before the slideUp function is even done executing. I want it so that the other screen waits until the slideUp function is done executing until the other screen shows up. Here is the main Javascript:

$('#sidebar ul li a').click(function(){ 

    $('#sidebar ul .clicked').removeClass('clicked'); // when an <a> is clicked, remove .clicked class from any other <a>'s

    $(this).addClass('clicked');

    hidePrevSlide(); //this calls slideUp in the current screen
    $(this).showCurrentSlide(); //this shows another screen before hidePrevSlide is even finished executing / sliding Up
});

I tried

hidePrevSlide(function(){
    $(this).showCurrentSlide();
});

but then this breaks the code for some reason. Is there any way to accomplish what I am doing?

Try this:

$('#sidebar ul li a').click(function(){ 

    $('#sidebar ul .clicked').removeClass('clicked'); // when an <a> is clicked, remove .clicked class from any other <a>'s

    $(this).addClass('clicked');

    var current_slide=$(this);
    hidePrevSlide(function(){
        current_slide.showCurrentSlide();
    });
    $(this).showCurrentSlide(); //this shows another screen before hidePrevSlide is even finished executing / sliding Up
});

I can see that you are running into a scoping issue. By storing $(this) before the function, you will be able to access that variable inside the function below.

For a small optimization, you should avoid using multiple $(this) so we can re-use our current_slide variable like so:

$('#sidebar ul li a').click(function(){ 
    var current_slide=$(this);

    $('#sidebar ul .clicked').removeClass('clicked'); // when an <a> is clicked, remove .clicked class from any other <a>'s

    current_slide.addClass('clicked');

    hidePrevSlide(function(){
        current_slide.showCurrentSlide();
    });
    current_slide.showCurrentSlide(); //this shows another screen before hidePrevSlide is even finished executing / sliding Up
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM