Javascript - 在函数内的函数中使用 $(this)

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

本文关键字:函数 this Javascript      更新时间:2023-09-26

基本上,有一个屏幕,如果你链接一个按钮,屏幕会向上滑动,然后出现另一个屏幕。问题是,slideUp() 函数需要一些时间来执行,并且在 slideUp 函数完成执行之前出现另一个屏幕。我希望它使另一个屏幕等到slideUp功能执行完毕,直到另一个屏幕出现。以下是主要的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
});

我试过了

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

但是由于某种原因,这会破坏代码。有什么方法可以完成我正在做的事情吗?

试试这个:

$('#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
});

我可以看到您遇到了范围界定问题。通过在函数之前存储$(this),您将能够在下面的函数中访问该变量。

对于一个小的优化,你应该避免使用多个$(this)这样我们就可以重用我们的current_slide变量,如下所示:

$('#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
});