Class name change Event in jQuery

后端 未结 2 838
轮回少年
轮回少年 2021-01-18 19:07

Is there a way to trigger a event in jQuery when an elements classes are changed?

Examples:


<
2条回答
  •  旧时难觅i
    2021-01-18 19:11

    I do not think this is possible.

    Events are based on user actions so click,dblclick,mouseover etc are all user actions.

    You may want to devise some kind of data block on each element and then build a small system that integrates into jQuery .class() and .attr() methods so that when your code updates a class it will add data to that element holding the previous class,

    then if the previous class is different to class being set then trigger your events.

    What i mean by integrate is

    var old_ClassFunc = $.fn.class; //Save it
    
    var $.fn.class = function()
    {
       if($(this).data('old-class'))
       {
          if($(this).data('class_callback'))#
          {
              $(this).data('class_callback')(this);
          }
       }
       $(this).data('old-class',$(this).attr('class')); //Update Data
       return old_class.apply(this,arguments);
    }
    

    then you can do like

    $('element').data('class_callback',function(context){
       alert('Element class has changed');
    })
    

    Hope this gives you some help

提交回复
热议问题