2016-09-12 14 views
0

アニメーション中にクリックイベントをバインドしたい場合は、次のコードは成功しますが、addscore() funcitonはそれ以上解決しませんか?クリックイベントを伴うjqueryアニメーション

function moveObstacle(target,distance){ 
     target.removeClass('animated bounce'); 
     target.animate({ left: distance },{ 
      duration: 10000, 
      progress: function(now, fx){ 
       $(this).addClass('animated bounce'); 
       $(this).click(function(){ 
        $(this).hide(); 
        addscore(); 
       }); 
      } 
     }); 

    } 


function addscore(){ 
     score2++; 
     if(score2 == 10){ 
      score1++; score2 = 0; 
     } 
     $('.scoreNum').eq(0).html(score1); 
     $('.scoreNum').eq(1).html(score2); 
    } 
+0

進捗コールバックが起動されるたびに、新しいクリックイベントを結合している、その理由! –

+0

アニメーション中に画像をクリックすると、スコアが追加されます。 – Fan

答えて

1

1つのオプションは、進捗関数の外クリックイベントハンドラを割り当て、:animated

をチェックしています

「アニメーションバウンス」クラスが必要な理由は明らかではありませんので、このままにしておきますが、質問には必要ないように思われます。

追加完了:時間が経過したときにターゲットを非表示にするアクション。

function moveObstacle(target,distance){ 
    target.removeClass('animated bounce'); 
    target.click(function() { 
     if ($(this).is(":animated")) { 
      $(this).hide(); 
      addscore(); 
     }); 
    }); 
    target.animate({ left: distance },{ 
     duration: 10000, 
     progress: function(now, fx){ 
      $(this).addClass('animated bounce'); 
     }, 
     complete: function() { 
      $(this).hide(); 
     } 
    }); 
} 

代替は、それが起動時にクリックを割り当て、それが停止したときにそれを削除することです:

function moveObstacle(target,distance){ 
    target.removeClass('animated bounce'); 
    target.click(function() { 
     $(this).hide(); 
     addscore(); 
    }); 
    target.animate({ left: distance },{ 
     duration: 10000, 
     progress: function(now, fx){ 
      $(this).addClass('animated bounce'); 
     }, 
     complete: function() { 
      target.off("click"); 
     } 
    }); 
} 
0

bind()メソッドとunbind()メソッドを使用すると簡単に解決できます。下記のようにコードを変更してください。

$(this).unbind('click').bind('click'function(){ 
    $(this).hide(); 
    addscore(); 
}); 
+0

私は実際にOPが進捗状況のコールバックの中にそれを設定する理由を知りません。 –

+0

はい、そうです。しかし、どのようにこれが解決策であるか。 –

0

あなたのイベントをバインドとアンバインドするfonction「オン」「オフ」とを使用することができます。

$(this).off('click').on('click', function(){ 
    $(this).hide(); 
    addscore(); 
}); 

他の方法は、あなたのアニメーションの開始は、(A.Wolffによって提案された場合にのみ、あなたのイベントをバインドすることです)

target.animate({ 
    left: distance 
}, { 
    duration: 10000, 
    start: function(fx) { 
    $(this).click(function() { 
     $(this).hide(); 
     addscore(); 
    }); 
    }, 
    progress: function(now, fx) { 
    $(this).addClass('animated bounce'); 
    } 
}); 
+0

これは、不正なコードロジックに関する回避策に過ぎません。少なくともOPは '進捗 'ではなく'開始 'を使うべきです。クリックイベントを委任するだけの方がいいでしょう –

関連する問題