1

次のスクリプトは、ajaxを使用してお気に入りボタンの外観を変更したり、MySQLテーブルにデータを送信/削除したりするように設計されています。

$(document).ready(function() {
jQuery("input.before").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');
      }, 
      error: function() {
        jQuery('#error').html('<div>Error! Unable to add favourite.</div>');
      }
    });
});

jQuery("input.after").click(function(){
   var $this = $(this);
   jQuery.ajax({       
      url: 'removefav.php',
      type: 'POST',
      data: {'id': $this.closest("div").attr("id"),is_ajax: 1},
      success: function(html) {
        $this.removeClass('after');
        $this.addClass('before');
      }, 
      error: function() {
        jQuery('#error').html('<div>Error! Unable to remove favourite.</div>');
      }
    });
});
});

これは、いくつかのボタンの1つをクリックすることによってトリガーされます。

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

スクリプトの最初のセクションでは、クラス'before'が削除され、クラス'after'が期待どおりに追加されますが、クラス'after'のボタンをクリックしようとすると、スクリプトの2番目のセクションが機能しません。つまり、ボタンのクラスは「前」に戻されません。なぜこれが機能しないのか誰かに教えてもらえますか?

4

1 に答える 1

3

最初のクリックハンドラーは、その時点でクラスのボタンにバインドされています。つまり、2番目のハンドラーbeforeによって返され、同じであるアイテムは、特定のクラスのボタンのイベントをいつでも使用して、イベント委任を使用します。jQuery("input.before").on()

$(document).ready(function() {
jQuery(document).on("click", "input.before", 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');
      }, 
      error: function() {
        jQuery('#error').html('<div>Error! Unable to add favourite.</div>');
      }
    });
});

jQuery(document).on("click", "input.after", function(){
   var $this = $(this);
   jQuery.ajax({       
      url: 'removefav.php',
      type: 'POST',
      data: {'id': $this.closest("div").attr("id"),is_ajax: 1},
      success: function(html) {
        $this.removeClass('after');
        $this.addClass('before');
      }, 
      error: function() {
        jQuery('#error').html('<div>Error! Unable to remove favourite.</div>');
      }
    });
});
});
于 2012-08-05T23:42:41.850 に答える