如何将回调函数添加到jQuery的addClass方法?
我正在使用Google和Markdown的Prettify,我希望每次在markdown textarea
添加pre
编码时再次调用prettyPrint()
函数。
这是我的实际代码:
if($('#wmd-preview').length > 0) { $('#wmd-preview').on('DOMNodeInserted DOMNodeRemoved',function(){ $(this).find("pre").not('.prettyprint').addClass("prettyprint"); }); }
但我想要的是:
$(this).find("pre").not('.prettyprint').addClass("prettyprint",function(){ prettyPrint(); });
有没有可能的方法来实现这一目标?
据我了解,你需要这个:
$(this).find("pre").not('.prettyprint').each(function(){ $(this).addClass("prettyprint"); prettyPrint(); })
你可以扩展.addClass()
jquery的方法让它接受一个回调函数:
;(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);
然后像往常一样使用它:
$('pre:not(.prettyprint)').addClass('prettyprint',prettyPrint);
addClass
jQuery函数在参数中没有回调。
在文档中阅读更多相关信息。
我认为这对你有用:
// prettyprint class is added $(this).find("pre").not('.prettyprint').addClass("prettyprint"); // after prettyprint class is added, prettyPrint function is called prettyPrint();