jQuery toggleClass callback how to?

2019-07-13 07:43发布

问题:

I have this simple jQuery event with toggleClass:

$(this).on("click", function() {
    $(this).toggleClass("fa-stop-circle");
});

I would like to call some method if fa-stop-circle is added. How can I monitor this event?

回答1:

toggleClass() doesn't have a callback, however you can check if the element has the class immediately after calling toggleClass(), like this:

$(this).on("click", function() {
    var $el = $(this).toggleClass("fa-stop-circle");
    if ($el.hasClass('fa-stop-circle')) {
        // do something...
    }
});

Working example



回答2:

You should use .done() in combination with .promise().

The promise will return deferred object;

Then done adds handler when deferred object is resolved.

$(this).toggleClass("fa-stop-circle").promise().done(function() {
    if ($this).hasClass("fa-stop-circle")) {
        // your code
    }
});


回答3:

You can add an if statement after the toggling

$(this).on("click", function() {
   var that = $(this);
   that.toggleClass("fa-stop-circle");
   if (that.hasClass('fa-stop-circle')) {
     // Execute your method
   }
});

UPDATE

You could create and use a function that fires a custom event every time toggleClass() gets executed and listen to this event in order to execute your method.

/**
*  Custom class for toggling classes
*  @param $elem {jQuery object}
*  @param classes {array}
*/
var customToggleClass = function($elem, classes) {
  if ($elem && $elem instanceof jQuery) {
    if (classes && classes.length > 0) {     
      if (classes.length == 1) {
        $elem.toggleClass(classes[0]);
        $(document).trigger('custom_toggleClass');
      } else if (classes.length == 2) {
        $elem.toggleClass(classes[0], classes[1]);
        $(document).trigger('custom_toggleClass');
      }      
    }
  }
}

$(document).on('click', '#test', function() {
  customToggleClass($('#test'), ['test_class_1', 'test_class_2']);
});

$(document).on('custom_toggleClass', function() {
  alert('Class changed!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<span id="test">Click me</span>



回答4:

The below code should work. You can use the promise() method and bind it to .done().

$(this).on("click", function() {
    $(this).toggleClass("fa-stop-circle").promise().done(function(){
         //call your method here
    });
});