Firing events on CSS class changes in jQuery

后端 未结 13 886
天涯浪人
天涯浪人 2020-11-22 04:45

How can I fire an event if a CSS class is added or changed using jQuery? Does changing of a CSS class fire the jQuery change() event?

13条回答
  •  囚心锁ツ
    2020-11-22 05:08

    Whenever you change a class in your script, you could use a trigger to raise your own event.

    $(this).addClass('someClass');
    $(mySelector).trigger('cssClassChanged')
    ....
    $(otherSelector).bind('cssClassChanged', data, function(){ do stuff });
    

    but otherwise, no, there's no baked-in way to fire an event when a class changes. change() only fires after focus leaves an input whose input has been altered.

    $(function() {
      var button = $('.clickme')
          , box = $('.box')
      ;
      
      button.on('click', function() { 
        box.removeClass('box');
        $(document).trigger('buttonClick');
      });
                
      $(document).on('buttonClick', function() {
        box.text('Clicked!');
      });
    });
    .box { background-color: red; }
    
    
    
    Hi

    More info on jQuery Triggers

提交回复
热议问题