0

基本的には画面があり、ボタンをリンクすると画面がスライドアップして別の画面が現れる。問題は、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();
});

しかし、これは何らかの理由でコードを壊します。私がやっていることを達成する方法はありますか?

4

1 に答える 1

1

これを試して:

$('#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
});
于 2013-10-13T16:30:24.667 に答える