函数中的 JavaScript 函数不起作用

javascript function within a function not working?

本文关键字:函数 不起作用 JavaScript      更新时间:2023-09-26

EDIT:新的问题是,即使current_slide.showCurrentSlide();函数位于hidePrevSlide函数内,showCurrentSLide代码也在hidePrevSlide中的动画完成之前执行。

我正在尝试创建一个网站,如果您单击

  • ,那么
  • 将添加一个类。然后,它将向上滑动当前可见屏幕并将其隐藏,然后显示与
  • 对应的屏幕(例如,如果
  • 是"主页",那么它将向上滑动当前现有屏幕并隐藏它,然后它应该"#homeSlide"屏幕)。这是我的代码。
    $(document).ready(function(){
        hideItems(); //this function basically hides all the screens / slides.. The words 'screen' and 'slides' are interchangeable for the time being.
        $('#homeSlide').fadeIn(1000); //the default screen to be shown is the home screen
        $('#homeSlide').addClass('current'); //to signify that this is the current visible screen
        $('#home').addClass('clicked'); //#home is the <li>, so it adds the .clicked class to the <li>
        $('#sidebar ul a li').click(function(){ //loops through all <li>'s in the sidebar if an <li> is clicked
            var current_slide = $(this);
            $('#sidebar ul .clicked').removeClass('clicked'); // when an <li> is clicked, remove .clicked class from any other <li>'s
            current_slide.addClass('clicked'); // add .clicked class to the clicked <li> ($(this))
            hidePrevSlide(function(){
                alert('enter showing step');
                current_slide.showCurrentSlide();
            });
        });
    });
    

    这是我的hidePrevSlide函数。

    function hidePrevSlide(){
        var test = $('.current').attr('id'); 
        test = "#" + test; // surrounds the id with a # and the word 'Slide'. This is the id of the screen which should slideUp
        $(test).slideUp( function () {
            $(test).hide();
            $(test).removeClass('current');
        });
    alert('finished hiding step. Should enter showing step now');
    };
    

    现在,当我运行代码时,它确实说"已完成隐藏步骤。应该现在输入显示步骤",但它没有说"输入显示步骤",因此它不会进入在hidePrevSlide功能完成后应执行的步骤。怎么来了?

  • hidePrevSlide需要调用回调函数。

    function hidePrevSlide(callback){
        var test = $('.current');
        test.slideUp( function () {
            test.hide();
            test.removeClass('current');
        });
        alert('finished hiding step. Should enter showing step now');
        callback();
    };
    

    我还删除了$(test)的使用。如果你有一个元素,就没有必要继续按ID搜索它。