Class name change Event in jQuery

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

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

Examples:


<
2条回答
  •  不思量自难忘°
    2021-01-18 19:27

    You might be able to workaround on a little hacky way. Hook .addClass() & .removeClass() like so:

    var _addClass    = $.fn.addClass,
        _removeClass = $.fn.removeClass;
    
    $.fn.addClass    = function(){
        // do whatever here
        return _addClass.apply(this, arguments);
    }
    
    $.fn.removeClass = function(){
        // do whatever here
        return _removeClass.apply(this, arguments);
    }
    

    That way, assuming you are just interested in watching elements class changes with jQuery, you can trigger whatever code on adding or removing classes. Again, just if you are using jQuery, for this example.

    Of course, you can hook and overwrite any javascript function that way.

    As Nick Craver mentioned in a comment, there are several other jQuery methods which can add or remove an elements class. You would have to hook all of those, namely:

    .addClass()
    .removeClass()
    .toggleClass()
    .removeAttr('class')
    .attr('class', 'changed')
    

    unless you know exactly which methods are called to manipulate a class, you would have to care about all of those.

提交回复
热议问题