How to add a callback function to the addClass method of jQuery?

霸气de小男生 提交于 2019-11-28 10:49:05

As far as I understand, you need this:

$(this).find("pre").not('.prettyprint').each(function(){
   $(this).addClass("prettyprint");
   prettyPrint();
})

You could extend .addClass() jquery's method to let it accept a callback function:

;(function ($) {
    var oAddClass = $.fn.addClass;
    $.fn.addClass = function () {
        for (var i in arguments) {
            var arg = arguments[i];
            if ( !! (arg && arg.constructor && arg.call && arg.apply)) {
                setTimeout(arg.bind(this));
                delete arguments[i];
            }
        }
        return oAddClass.apply(this, arguments);
    }

})(jQuery);

Then use it as usual:

 $('pre:not(.prettyprint)').addClass('prettyprint',prettyPrint);

The addClass jQuery function doesn't have a callback in arguments.

Read more about this in documentation.

I think that this sould work for you:

// prettyprint class is added
$(this).find("pre").not('.prettyprint').addClass("prettyprint");
// after prettyprint class is added, prettyPrint function is called
prettyPrint();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!