2012-04-09 16 views
1

Ajaxリクエストの開始時にdivを無効にして(クリックを受け付けないように)、Ajaxの完了時に再度有効にする必要があります。私はまた、プロセス中に表示されるロードGIFをしたい。私はこれがajaxStartajaxStopを使って達成できると思います。しかし、私が正しければ、これらは起動または停止するAjax要求に対して起動します。ここで問題が起こる。私はページに複数のdivを持っており、これらの誰かがAjaxリクエストを引き起こす可能性があります。クリックした「特定のdiv」を無効にする/有効にするにはどうすればいいですか?ajaxStartajaxStopまたはその他の方法を使用して、対応する読み込み中のGIFを表示/非表示にするにはどうすればいいですか?これにclickイベントのバインディング/バインド解除が含まれる場合は、jQuery on()との互換性を維持する必要があることに注意してください。Ajaxのdivの開始を無効にしてからAjaxで再度有効にしてください

HTMLは次のようになります。

$('body').on('click', '.button', function(e){ 
e.preventDefault(); 

    $.ajax({ 
     url  : ajaxVars.ajaxurl, 
     context : this, 
     type :'POST', 
     async : true, 
     cache : false, 
     timeout : 1000, 
     data : { action : 'test_action' }, 
     success : function(response) { 
      if (response == 1) { 
       $(this).toggleClass('white').toggleClass('green'); 
      } 
     }, 
     error : function() { 
      alert(error); 
     } 
    }); 
}); 

よろしく、ジョン

答えて

4

ボタンを無効にするには、単に現在のクラスボタンを変更します。

あなたはこれを使用することができます。

$('body').on('click', '.button', function(e){ 
e.preventDefault(); 

$(this).removeClass('button').addClass('disabledbutton'); 

$.ajax({ 
    url  : ajaxVars.ajaxurl, 
    context : this, 
    type :'POST', 
    async : true, 
    cache : false, 
    timeout : 1000, 
    data : { action : 'test_action' }, 
    success : function(response) { 
     if (response == 1) { 
      $(this).toggleClass('white').toggleClass('green'); 
      $(this).removeClass('disabledbutton').addClass('button'); 
     } 
    }, 
    error : function() { 
     alert(error); 
    } 

    }); 
}); 
+0

返信用のThx。 removeClassは.buttonクラスを削除しません。ただし、addClassは機能します。これはおそらく.buttonがon()イベントのセレクタとして使用されているのでしょうか? – John

+0

@Johnごめんなさい。これは間違っています:.removeClass( '。button')これは正しいです:.removeClass( 'button')私は自分の投稿を編集しました。 – EmRa228

+0

これは機能します!ソリューションのThx。 – John

0

単に無効にする/機能の動作を可能とするために、いくつかのヘルパー関数を作成する:Ajaxのための

<div class="button white"><img src="loading.gif" /></div> 
<div class="button white"><img src="loading.gif" /></div> 
<div class="button white"><img src="loading.gif" /></div> 

Javascriptがこのようになりますこれのためによく。クリックするとdisable fnが呼び出され、ajaxが成功するとenable関数が呼び出されます。

function disableButton(button) { 
    //disable actions 
} 

function enableButton(button) { 
    //enable actions 
} 

$('body').on('click', '.button', function(e){ 

    e.preventDefault(); 
    disableButton($(this)); 

    $.ajax({ 
     url  : ajaxVars.ajaxurl, 
     context : this, 
     type :'POST', 
     async : true, 
     cache : false, 
     timeout : 1000, 
     data : { action : 'test_action' }, 
     success : function(response) { 
      if (response == 1) { 
       $(this).toggleClass('white').toggleClass('green'); 
       enableButton($(this)); 
      } 
     }, 
     error : function() { 
      alert(error); 
     } 
    }); 
}); 
+0

Thxをを返信するために。この作業を行うために関数内でどのコードを使用すべきかを提案できますか?それは基本的に私が答えとして探していたものです。 – John

関連する問題