1

次の jQuery/ajax スクリプトがあります。

jQuery("input.button").click(function(){
   jQuery.ajax({       
      url: 'addfav.php',
      type: 'POST',
      data: {'id':jQuery(this).closest("div").attr("id"),is_ajax: 1},
      success: function(html) {
        jQuery(this).removeClass('before');
        jQuery(this).addClass('after');
        jQuery(this).attr('disabled', 'disabled');
      }, 
      error: function() {
        jQuery('#error').html('<div>Error! Unable to add food item.</div>');
      }
    });
});

次のようなボタンのクリックを処理します。

<div id="32"><input type="button" class="button before"/></div>
<div id="33"><input type="button" class="button before"/></div>

ただし、クリックしたクラス以外のクラスの追加と削除は機能しません。ID を持つ単一のボタンに対して機能します。つまり、次のようになります。

jQuery("input#button1").click(function(){

しかし、クラスを使用するときはそうではありません。ボタンにクラスを使用するだけで、クリックされたボタンにクラスを追加または削除するには、このスクリプトを取得するためにどのような変更を加える必要がありますか?

4

1 に答える 1

2

セレクターをキャッシュする必要があります。次のことを試してください。

jQuery("input.button").click(function(){
   var $this = $(this);
   jQuery.ajax({       
      url: 'addfav.php',
      type: 'POST',
      data: {'id': $this.closest("div").attr("id"),is_ajax: 1},
      success: function(html) {
        $this.removeClass('before');
        $this.addClass('after');
        $this.attr('disabled', 'disabled');
      }, 
      error: function() {
        jQuery('#error').html('<div>Error! Unable to add food item.</div>');
      }
    });
});
于 2012-08-05T22:56:31.397 に答える