问题
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