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

China☆狼群 提交于 2019-11-27 03:49:09

问题


I'm using Prettify from Google and Markdown and I want each time I find a pre code added in the markdown textarea to call again the prettyPrint() function.

This is my actual code:

if($('#wmd-preview').length > 0) {
  $('#wmd-preview').on('DOMNodeInserted DOMNodeRemoved',function(){
    $(this).find("pre").not('.prettyprint').addClass("prettyprint");
  });
}

But I want something like:

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

Is there any possible way to achieve this?


回答1:


As far as I understand, you need this:

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



回答2:


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);



回答3:


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();


来源:https://stackoverflow.com/questions/14567990/how-to-add-a-callback-function-to-the-addclass-method-of-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!